Check If Any Value Of A Dictionary Matches A Condition
How does a python programmer check if any value of a dictionary matches a condition (is greater than 0 in my case). I'm looking for the most 'pythonic' way that has minimal perform
Solution 1:
You can use any
[docs]:
>>> pairs = { 'word1':0, 'word2':0, 'word3':2000, 'word4':64, 'word5':0, 'wordn':8 }
>>> any(v > 0 for v in pairs.itervalues())
True
>>> any(v > 3000 for v in pairs.itervalues())
False
See also all
[docs]:
>>> all(v > 0 for v in pairs.itervalues())
False
>>> all(v < 3000 for v in pairs.itervalues())
True
Since you're using Python 2.7, .itervalues()
is probably a little better than .values()
because it doesn't create a new list.
Solution 2:
Python 3.x Update
In Python 3, direct iteration over mappings works the same way as it does in Python 2. There are no method based equivalents - the semantic equivalents of d.itervalues() and d.iteritems() in Python 3 are iter(d.values()) and iter(d.items()).
According to the docs, you should use iter(d.values())
, instead of d.itervalues()
:
>>> pairs = { 'word1':0, 'word2':0, 'word3':2000, 'word4':64, 'word5':0, 'wordn':8 }
>>> any(v > 0 for v in iter(pairs.values()))
True
>>> any(v > 3000 for v in iter(pairs.values()))
False
Post a Comment for "Check If Any Value Of A Dictionary Matches A Condition"