Search code examples
pythonpython-3.xlistdictionarycollections

How to retrieve the keys of duplicate lists in a dictionary?


How to retrieve the keys of duplicate list-values?

d1 = {'a': ['abc','cde','abc'], 'b': ['a', 'd', 'f'], 'c': ['abc','cde','abc']} 

Expected output: ['a','c'] or {'a':'c'}.

I tried this code:

from collections import Counter
d1 = {1: [1], 2: [1, 2]}
Counter([r[1] for r in d1.items()])
    

But I get an error:

TypeError: unhashable type: 'list'

I also tried with Counter(d1.values()), but get the same error.

Is this the right approach? Or is there a better way?


Solution

  • One way is to simply use set() on values.

    l=[]
    for k,v in d1.items():
        if len(v)!=len(set(v)):  # if there are duplicate values then len of set will not be equal to len of list
            l.append(k)
    
    print(l)
    #['a', 'c']
    

    With List Comprehension:

    [k for k,v in d1.items() if len(v)!=len(set(v))]