I have a dictionary, and I'm trying to check for the rare occurrence of all values having the same numerical value, say 1. How would I go about doing this in an efficient manner?
Given a dictionary, test if all its values are the same. Input : test_dict = {"Gfg" : 8, "is" : 8, "Best" : 8} Output : True Explanation : All element values are same, 8. Input : test_dict = {"Gfg" : 8, "is" : 8, "Best" : 9} Output : False Explanation : All element values not same.
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.
Use == to check equality of two dictionaries Use == to check if two dictionaries contain the same set of key: value pairs.
To check if a key-value pair exists in a dictionary, i.e., if a dictionary has/contains a pair, use the in operator and the items() method. Specify a tuple (key, value) . Use not in to check if a pair does not exist in a dictionary.
I will assume you meant the same value:
d = {'a':1, 'b':1, 'c':1}
len(set(d.values()))==1 # -> True
If you want to check for a specific value, how about
testval = 1
all(val==testval for val in d.values()) # -> True
this code will most often fail early (quickly)
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