Python | Find keys with duplicate values in dictionary
Last Updated :
31 Mar, 2023
Given a dictionary, the task is to find keys with duplicate values. Let's discuss a few methods for the same.
Method #1: Using Naive approach In this method first, we convert dictionary values to keys with the inverse mapping and then find the duplicate keys
Python3
# Python code to demonstrate
# finding duplicate values from a dictionary
# initialising dictionary
ini_dict = {'a':1, 'b':2, 'c':3, 'd':2}
# printing initial_dictionary
print("initial_dictionary", str(ini_dict))
# finding duplicate values
# from dictionary
# using a naive approach
rev_dict = {}
for key, value in ini_dict.items():
rev_dict.setdefault(value, set()).add(key)
result = [key for key, values in rev_dict.items()
if len(values) > 1]
# printing result
print("duplicate values", str(result))
Output:initial_dictionary {'c': 3, 'b': 2, 'd': 2, 'a': 1}
duplicate values [2]
Time Complexity: O(n), where n is the number of elements in the dictionary.
Auxiliary Space: O(n)
Method #2: Using flipping dictionary
Python3
# Python code to demonstrate
# finding duplicate values from dictionary
# initialising dictionary
ini_dict = {'a':1, 'b':2, 'c':3, 'd':2}
# printing initial_dictionary
print("initial_dictionary", str(ini_dict))
# finding duplicate values
# from dictionary using flip
flipped = {}
for key, value in ini_dict.items():
if value not in flipped:
flipped[value] = [key]
else:
flipped[value].append(key)
# printing result
print("final_dictionary", str(flipped))
Output:initial_dictionary {'a': 1, 'c': 3, 'd': 2, 'b': 2}
final_dictionary {1: ['a'], 2: ['d', 'b'], 3: ['c']}
Time complexity: O(n), where n is the number of key-value pairs in the input dictionary.
Auxiliary space: O(n), where n is the number of key-value pairs in the input dictionary.
Method #3: Using chain and set Suppose you need to find keys having duplicate values.
Python3
# Python code to demonstrate
# finding duplicate values from dictionary
from itertools import chain
# initialising dictionary
ini_dict = {'a':1, 'b':2, 'c':3, 'd':2}
# printing initial_dictionary
print("initial_dictionary", str(ini_dict))
# finding duplicate values
# from dictionary using set
rev_dict = {}
for key, value in ini_dict.items():
rev_dict.setdefault(value, set()).add(key)
result = set(chain.from_iterable(
values for key, values in rev_dict.items()
if len(values) > 1))
# printing result
print("resultant key", str(result))
Output:initial_dictionary {'b': 2, 'd': 2, 'c': 3, 'a': 1}
resultant key {'d', 'b'}
Instead of
Python3
result = set(chain.from_iterable(
values for key, values in rev_dict.items()
if len(values) > 1))
Use this:
Python3
result = filter(lambda x: len(x)>1, rev_dict.values())
print(list(result))
Using collections:
One approach not mentioned is to use a Counter from the collections module. A Counter is a dictionary subclass that keeps track of the number of occurrences of each element. You can use a Counter to find the keys with duplicate values by counting the values and creating a new dictionary with only the keys whose value has a count greater than 1.
Here's an example of how to do this:
Python3
from collections import Counter
# Initialize the dictionary
ini_dict = {'a':1, 'b':2, 'c':3, 'd':2}
# Create a Counter from the dictionary values
counts = Counter(ini_dict.values())
# Create a new dictionary with only the keys whose value has a count greater than 1
result = {k: v for k, v in ini_dict.items() if counts[v] > 1}
print(result.keys())
#This code is contributed by Edula Vinay Kumar Reddy
Outputdict_keys(['b', 'd'])
Time complexity: O(n)
Auxiliary Space: O(n)
Method #5: Using Counter
This method involves using the Counter module from the collections library to count the occurrences of values in the dictionary. Then extract the keys with count greater than 1 to get the duplicate values.
Step-by-Step Approach:
- Import the Counter module from the collections library.
- Initialize the dictionary with values.
- Create a Counter object using the dictionary values.
- Iterate through the Counter object and extract the keys with count greater than 1 to get the duplicate values.
- Print the duplicate values.
Below is the implementation of the above approach:
Python3
# Python code to demonstrate
# finding duplicate values from a dictionary
# import Counter module from collections library
from collections import Counter
# initialising dictionary
ini_dict = {'a':1, 'b':2, 'c':3, 'd':2}
# printing initial_dictionary
print("initial_dictionary", str(ini_dict))
# finding duplicate values
# from dictionary
# using Counter
count_dict = Counter(ini_dict.values())
result = [key for key, value in ini_dict.items()
if count_dict[value] > 1]
# printing result
print("duplicate values", str(result))
Outputinitial_dictionary {'a': 1, 'b': 2, 'c': 3, 'd': 2}
duplicate values ['b', 'd']
Time Complexity: O(n), where n is the number of elements in the dictionary.
Auxiliary Space: O(n), where n is the number of elements in the dictionary.
Similar Reads
Python - Remove duplicate values in dictionary Sometimes, while working with Python dictionaries, we can have problem in which we need to perform the removal of all the duplicate values of dictionary, and we are not concerned if any key get removed in the process. This kind of application can occur in school programming and day-day programming.
8 min read
Python - Merge Dictionaries List with duplicate Keys Given two List of dictionaries with possible duplicate keys, write a Python program to perform merge. Examples: Input : test_list1 = [{"gfg" : 1, "best" : 4}, {"geeks" : 10, "good" : 15}, {"love" : "gfg"}], test_list2 = [{"gfg" : 6}, {"better" : 3, "for" : 10, "geeks" : 1}, {"gfg" : 10}] Output : [{
4 min read
Python Program to display keys with same values in a dictionary List Given a list with all dictionary elements, the task is to write a Python program to extract keys having similar values across all dictionaries. Examples: Input : test_list = [{"Gfg": 5, "is" : 8, "best" : 0}, {"Gfg": 5, "is" : 1, "best" : 0}, {"Gfg": 5, "is" : 0, "best" : 0}] Output : ['Gfg', 'best'
5 min read
Python | Test if key exists in tuple keys dictionary Sometimes, while working with dictionary data, we need to check if a particular key is present in the dictionary. If keys are elementary, the solution to a problem in discussed and easier to solve. But sometimes, we can have a tuple as key of the dictionary. Let's discuss certain ways in which this
7 min read
Python - Pairs with multiple similar values in dictionary Sometimes, while working with dictionaries, we can have a problem in which we need to keep the dictionaries which are having similar key's value in other dictionary. This is a very specific problem. This can have applications in web development domain. Lets discuss certain ways in which this task ca
4 min read