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.

quamrana
  • 37,849
  • 12
  • 53
  • 71

3 Answers3

5
dicts = [d, e, f]    
if all([i['b'] >= 3 for i in dicts]):
    func()
Paul_0
  • 358
  • 4
  • 11
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()
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
ksohan
  • 1,165
  • 2
  • 9
  • 23
  • 1
    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 https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops – Tomerikoo May 30 '22 at 16:45
  • 1
    Added your suggested version also. Thanks @Tomerikoo – ksohan May 30 '22 at 17:28
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()
EnriqueBet
  • 1,482
  • 2
  • 15
  • 23