Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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
like image 505
Firebowl2000 Avatar asked Sep 11 '12 18:09

Firebowl2000


People also ask

Can == operator be used on dictionaries?

According to the python doc, you can indeed use the == operator on dictionaries.

How do you check if something is in the values of a dictionary?

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.

How do you compare values 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.

How do you check if an item is in a dictionary Python?

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.


1 Answers

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.

like image 80
DSM Avatar answered Sep 21 '22 01:09

DSM