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?


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]):

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")
>>> unanimous("AAAAAAAAAAAAB")

Use unanimous to see if all dict values are the same:

>>> dd = { 'a':1, 'b':1, 'c':1 }
>>> print unanimous(dd.values())

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

Need Your Help

JSTL if tag for equal strings

java jsp websphere jstl jsp-tags

I've got a variable from an object on my JSP page:

How does Bundler know what environment to use?

ruby-on-rails bundler ruby-on-rails-3

Here's probably a very "newbieish" question on Bundler, but I'm wondering how bundle install knows what environment to use or how to set it? Or do I even need to? My problem is that I've grouped my...