Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if values in a dictionary all have the same value X?

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?

like image 306
Incognito Avatar asked Feb 22 '11 03:02

Incognito


People also ask

How do you check if all values are the same in a dictionary?

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.

How do you compare values in a dictionary?

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 two values are the same in a dictionary Python?

Use == to check equality of two dictionaries Use == to check if two dictionaries contain the same set of key: value pairs.

How do you check if a key-value pair is in a dictionary?

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.


1 Answers

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)

like image 90
Hugh Bothwell Avatar answered Oct 12 '22 14:10

Hugh Bothwell