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 containing all the keys for values โ€‹โ€‹that appear more than once:

 mylist = [1,2,3,4] 

The value 'mango' appears only once, so key 5 not in mylist .

How can i achieve this?

+5
source share
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] 
+6
source

On python 2.7, an easy way for a small dict. Better solution, use collections.Counter.

 >>> [k for k, v in mydict.items() if mydict.values().count(v) > 1] [1, 2, 3, 4] 
+2
source

Source: https://habr.com/ru/post/1233399/


All Articles