- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
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'}]
- Related Articles
- How to create Python dictionary with duplicate keys?
- Keys associated with Values in Dictionary in Python
- Append Dictionary Keys and Values (In order ) in dictionary using Python
- Python – Limit the values to keys in a Dictionary List
- How to convert Python dictionary keys/values to lowercase?
- How to insert new keys/values into Python dictionary?
- Python - Combine two dictionary adding values for common keys
- Python – Merge Dictionaries List with duplicate Keys
- Python dictionary with keys having multiple inputs
- Properties of Dictionary Keys in Python
- How to create Python dictionary from list of keys and values?
- How to split Python dictionary into multiple keys, dividing the values equally?
- Get dictionary keys as a list in Python
- Why must dictionary keys be immutable in Python?
- Python Extract specific keys from dictionary?
