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 performance-impact.
my dictionary:
pairs = { 'word1':0, 'word2':0, 'word3':2000, 'word4':64, 'word5':0, 'wordn':8 }
I used these 2 (monstrous?) methods so far.
1:
options = pairs.values() # extract values
for i in options:
if i > 0:
return True
return False
2:
options = sorted(pairs.items(), key=lambda e: e[1], reverse=True) # rank from max to min
if options[0][1] > 0:
return True
else:
return False
According to the python doc, you can indeed use the == operator on dictionaries.
To check if a value exists in a dictionary, i.e., if a dictionary has/contains a value, use the in operator and the values() method. Use not in to check if a value does not exist in a dictionary.
Python List cmp() Method. The compare method cmp() is used in Python to compare values and keys of two dictionaries. If method returns 0 if both dictionaries are equal, 1 if dic1 > dict2 and -1 if dict1 < dict2.
Check If Key Exists using has_key() method Using has_key() method returns true if a given key is available in the dictionary, otherwise, it returns a false. With the Inbuilt method has_key(), use the if statement to check if the key is present in the dictionary or not.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With