Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find dictionary keys with duplicate values

some_dict = {"firstname": "Albert", "nickname": "Albert", "surname": "Likins", "username": "Angel"}

I would like to return the keys of my dict where their value exists for more than one time.

Could some one show me how to implement this?

a_list = []
for k,v in  some_dict.iteritems():
    if v in some_dict.values() and v != some_dict.keys(k):
        a_list.append(k)
like image 790
lzc Avatar asked Dec 19 '13 02:12

lzc


People also ask

Can key in dictionary have duplicate values?

The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.

Can dictionary have duplicate keys Python?

Dictionaries in Python First, a given key can appear in a dictionary only once. Duplicate keys are not allowed.

Can dictionary have duplicate keys in C#?

In Dictionary, the key cannot be null, but value can be. In Dictionary, key must be unique. Duplicate keys are not allowed if you try to use duplicate key then compiler will throw an exception. In Dictionary, you can only store same types of elements.


2 Answers

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'}
like image 99
abarnert Avatar answered Sep 22 '22 12:09

abarnert


I would start by flipping the keys and values:

flipped = {}

for key, value in d.items():
    if value not in flipped:
        flipped[value] = [key]
    else:
        flipped[value].append(key)

You could do this more efficiently with collections.defaultdict(set). For your dictionary, flipped will look like:

{
    'Albert': ['nickname', 'firstname'],
    'Angel':  ['username'],
    'Likins': ['surname']
}
like image 23
Blender Avatar answered Sep 24 '22 12:09

Blender