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?
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]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With