Find keys with duplicate values in dictionary in Python


While dealing with dictionaries, we may come across situation when there are duplicate values in the dictionary while obviously the keys remain unique. In this article we will see how we can achieve thi.

Exchanging keys and values

We exchange the keys with values of the dictionaries and then keep appending the values associated with a given key. This way the duplicate values get clubbed and we can see them in the resulting new dictionary.

Example

 Live Demo

dictA = {'Sun': 5, 'Mon': 3, 'Tue': 5, 'Wed': 3}

print("Given Dictionary :", dictA)

k_v_exchanged = {}

for key, value in dictA.items():
   if value not in k_v_exchanged:
      k_v_exchanged[value] = [key]
   else:
      k_v_exchanged[value].append(key)

# Result
print("New Dictionary:", k_v_exchanged)

Output

Running the above code gives us the following result −

Given Dictionary : {'Sun': 5, 'Mon': 3, 'Tue': 5, 'Wed': 3}
New Dictionary: {5: ['Sun', 'Tue'], 3: ['Mon', 'Wed']}

With set

we follow a similar approach here. Here also we create a new dictionary from the existing dictionary using set function and adding the keys with duplicate values. Finally we filter out the values where the length is greater than 1 and mark them as duplicates.

Example

 Live Demo

dictA = {'Sun': 5, 'Mon': 3, 'Tue': 5, 'Wed': 4}

print("Given Dictionary :", dictA)

dictB = {}
for key, value in dictA.items():
   dictB.setdefault(value, set()).add(key)

res = filter(lambda x: len(x) >1, dictB.values())

# Result
print("New Dictionary:",list(res))

Output

Running the above code gives us the following result −

Given Dictionary : {'Sun': 5, 'Mon': 3, 'Tue': 5, 'Wed': 4}
New Dictionary: [{'Tue', 'Sun'}]

Updated on: 26-Aug-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements