-1

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?

Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44
Learner
  • 61
  • 6
  • Does this answer your question? [Use a list as the key in a Python dict](https://stackoverflow.com/questions/30274185/use-a-list-as-the-key-in-a-python-dict) – mkrieger1 May 24 '23 at 07:40
  • It's not clear what you mean by duplicate. `['abc','cde','abc']` is a duplicate because it is the value of keys `a` and `c`, but also `'abc'` is a duplicate because it appears in twice in both `a` and `c`. Which do you mean? – Mark May 24 '23 at 07:48
  • @Mark Duplicate here as referred as, each items of the list-value ['abc','cde','abc']. In the given example, we can say keys 'a' and 'c' have same values (duplicate). – Learner May 24 '23 at 08:18

3 Answers3

1

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))]
Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44
0

You can create a reverse mapping that maps each sub-list to a list of keys, and output those lists of keys with lengths greater than 1. To make a list hashable as a key, convert it to a tuple first:

mapping = {}
for key, lst in d1.items():
    mapping.setdefault(tuple(lst), []).append(key)
print(*(keys for keys in mapping.values() if len(keys) > 1))

This outputs:

['a', 'c']

Demo: https://replit.com/@blhsing/GlumImmaculateDebugger

blhsing
  • 91,368
  • 6
  • 71
  • 106
0
d1 = {'a': ['abc', 'cde', 'abc'], 'b': ['a', 'd', 'f'], 'c': ['abc', 'cde', 'abc']}
duplicates = []

keys = list(d1.keys())

for index in range(len(keys)):
    for i in range(index + 1, len(keys)):
        if d1[keys[index]] == d1[keys[i]] and keys[index] not in duplicates:
            duplicates.append(keys[index])
            duplicates.append(keys[i])

print(duplicates)