0

If I have:

d = {'a': 1, 'b': 3} e = {'a': 2, 'b': 6} f = {'a': 1, 'b': 4} 

How would I check that values of the 'b' key in all dictionaries is above 2 and then execute a function?

I have tried:

dicts = [d, e, f] for i in dicts: if i['b'] >= 3: func() 

However, this calls the function 3 times, whereas I only want to call it once all arguments are met.

1
  • Count how many times i['b'] >= 3 is true. Commented May 30, 2022 at 16:37

3 Answers 3

5
dicts = [d, e, f] if all([i['b'] >= 3 for i in dicts]): func() 
Sign up to request clarification or add additional context in comments.

Comments

1

You can use a variable to keep track:

d = {'a': 1, 'b': 3} e = {'a': 2, 'b': 6} f = {'a': 1, 'b': 4} dicts = [d, e, f] callFunct = True for i in dicts: if i['b'] < 3: callFunct = False if callFunct: func() 

Another version without a flag was suggested by @Tomerikoo in the comment:

d = {'a': 1, 'b': 3} e = {'a': 2, 'b': 6} f = {'a': 1, 'b': 4} dicts = [d,e,f] for i in dicts: if i['b'] < 3: break else: func() 

2 Comments

No flag is needed (callFunct). Just put break under the if and call the function inside an else (at the level of the for loop) see docs.python.org/3/tutorial/…
Added your suggested version also. Thanks @Tomerikoo
0

A possible solution is to add a counter that tells you whether the dictionary had the key you were looking for:

d = {'a': 1, 'b': 3} e = {'a': 2, 'b': 6} f = {'a': 1, 'b': 4} dicts = [d,e,f] counter = 0 for d in dicts: if d.get("b") and d["b"] >=3: counter += 1 if counter == len(dicts): func() 

3 Comments

You could just do if d.get('b', 0) >= 3. If the key is not there, the condition will be false
yes, but I'm unsure if the default value should be 0
It's < 3 so it will always be false...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.