How can I check if all values in a dictionary are equal? [duplicate]

If you are looking to see if all of the values of a dictionary are the same, then you could do something like:

d1 = {"k1": "v2", "k2": "v2", "k3": "v2"}
if len(set(d1.values())) == 1:
    print("All values are the same")

Explanation: d1.values() contains all of the values, set() de-duplicates it, and len() provides the length. If there is only 1 de-duplicated value, then all of the values must be the same.

If you are looking specifically for the count of values that are the same (even when they are not all the same, then you could use a variation of this, comparing the number of de-duplicated values to the number of keys.


This should work -

d1={'k1':'v2','k2':'v2','k3':'v2'}
l={}
for v in d1.keys():
    l[d1[v]] = list(d1.values()).count(d1[v])

if 0 in list(l.values()):
    print('No keys have same values!')
else:
    print(f'{list(l.values())[0]} keys have same values')

If your values can be keys of a dictionary, in other words is of hashable type, then you can do very fast (linear complexity) algorithm using counting dictionary (and you str type is hashable).

Following code output at the end all duplicates (values that appear more than once), duplicates are shown as pairs of value and number of repetitions.

Try it online!

d1={'k1':'v2','k2':'v2','k3':'v2'}

cnt = {}
for e in d1.values():
    cnt[e] = cnt.get(e, 0) + 1
cnt = sorted(cnt.items(), key = lambda e: e[1], reverse = True)

if len(cnt) > 0 and cnt[0][1] > 1:
    print('There are duplicates:', {a : b for a, b in cnt if b > 1})
else:
    print('No keys have same values!')

Output:

There are duplicates: {'v2': 3}

Same code as above can be implemented shorter using standard library class collections.Counter.

Try it online!

import collections

d1={'k1':'v2','k2':'v2','k3':'v2'}

cnt = collections.Counter(d1.values()).most_common()

if len(cnt) > 0 and cnt[0][1] > 1:
    print('There are duplicates:', {a : b for a, b in cnt if b > 1})
else:
    print('No keys have same values!')

Output:

There are duplicates: {'v2': 3}