How do I check if values in a dictionary all have

2020-07-10 07:23发布

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?

4条回答
祖国的老花朵
2楼-- · 2020-07-10 07:35

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
查看更多
对你真心纯属浪费
3楼-- · 2020-07-10 07:45

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
查看更多
叼着烟拽天下
4楼-- · 2020-07-10 07:49

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
查看更多
冷血范
5楼-- · 2020-07-10 07:52

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)

查看更多
登录 后发表回答