Find dictionary keys with duplicate values

First, flip the dictionary around into a reverse multidict, mapping each value to all of the keys it maps to. Like this:

>>> some_dict = {"firstname":"Albert","nickname":"Albert","surname":"Likins","username":"Angel"}
>>> rev_multidict = {}
>>> for key, value in some_dict.items():
...     rev_multidict.setdefault(value, set()).add(key)

Now, you’re just looking for the keys in the multidict that have more than 1 value. That’s easy:

>>> [key for key, values in rev_multidict.items() if len(values) > 1]
['Albert']

Except the multidict keys are the original dict values. So, this is each repeated value, not all of the keys matching each repeated value. But you know what is all of the keys matching each repeated value?

>>> [values for key, values in rev_multidict.items() if len(values) > 1]
[{'firstname', 'nickname'}]

Of course that gives you a list of sets. If you want to flatten that into a single list or set, that’s easy. You can use chain.from_iterable, or a nested comprehension, or any of the other usual tricks. For example:

>>> set(chain.from_iterable(values for key, values in rev_multidict.items() if len(values) > 1))
{'firstname', 'nickname'}

Leave a Comment