Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find keys for values that appear more than once

I have a dictionary as follows:

mydict ={1:'apple',2:'banana',3:'banana',4:'apple',5:'mango'}

I want to compute a list that contains all the keys for values that appear more than once:

mylist = [1,2,3,4]

Value 'mango' only appears once, and therefore key 5 is not present in mylist.

How can I achieve this?

like image 990
akira Avatar asked Oct 10 '15 06:10

akira


2 Answers

You can use Counter to do this:

>>> from collections import Counter 
>>> c = Counter(mydict.values())
>>> [k for k, v in mydict.items() if c[v] > 1]
[1, 2, 3, 4]
like image 195
styvane Avatar answered Sep 23 '22 14:09

styvane


On python 2.7, simple way for small dict. Better solution, use collections.Counter.

>>> [k for k, v in mydict.items() if mydict.values().count(v) > 1]
[1, 2, 3, 4]
like image 35
luoluo Avatar answered Sep 21 '22 14:09

luoluo