I have a dictionary, and I'm trying to check f开发者_StackOverflow社区or the rare occurrence of all values having the same numerical value, say 1. How would I go about doing this in an efficient manner?
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)
You cannot have key*s* with the same value. This means that there is only one key in your dictionary, because every subsequent one will overwrite the previous. If you are concerned that all keys have the values which are one. Then you do something like this:
if set(your_dict.values()) == set([1]):
pass
Inspired by some of the discussion from this other question:
>>> def unanimous(seq):
... it = iter(seq)
... try:
... first = next(it)
... except StopIteration:
... return True
... else:
... return all(i == first for i in it)
...
>>> unanimous("AAAAAAAAAAAAA")
True
>>> unanimous("AAAAAAAAAAAAB")
False
Use unanimous
to see if all dict values are the same:
>>> dd = { 'a':1, 'b':1, 'c':1 }
>>> print unanimous(dd.values())
True
You can also try this:
>>> test
{'c': 3, 'b': 3, 'd': 3, 'f': 3}
>>> z=dict(zip(test.values(),test.keys()))
>>> z
{3: 'f'}
>>> len(z) == 1
True
精彩评论