Related Articles
Python | Find keys with duplicate values in dictionary
• Last Updated : 07 Aug, 2019

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

 # Python code to demonstrate # finding duplicate values from a dictionary  # initialising dictionaryini_dict = {'a':1, 'b':2, 'c':3, 'd':2}  # printing initial_dictionaryprint("initial_dictionary", str(ini_dict))  # finding duplicate values# from dictionary# using a naive approachrev_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 resultprint("duplicate values", str(result))
Output:
initial_dictionary {'c': 3, 'b': 2, 'd': 2, 'a': 1}
duplicate values [2]

Method #2: Using flipping dictionary

 # Python code to demonstrate # finding duplicate values from dictionary  # initialising dictionaryini_dict = {'a':1, 'b':2, 'c':3, 'd':2}  # printing initial_dictionaryprint("initial_dictionary", str(ini_dict))  # finding duplicate values# from dictionary using flipflipped = {}  for key, value in ini_dict.items():    if value not in flipped:        flipped[value] = [key]    else:        flipped[value].append(key)  # printing resultprint("final_dictionary", str(flipped))
Output:

initial_dictionary {'a': 1, 'c': 3, 'd': 2, 'b': 2}
final_dictionary {1: ['a'], 2: ['d', 'b'], 3: ['c']}

Method #3: Using chain and set

Suppose you need to find keys having duplicate values.

 # Python code to demonstrate # finding duplicate values from dictionaryfrom itertools import chain  # initialising dictionaryini_dict = {'a':1, 'b':2, 'c':3, 'd':2}  # printing initial_dictionaryprint("initial_dictionary", str(ini_dict))  # finding duplicate values# from dictionary using setrev_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 resultprint("resultant key", str(result))
Output:
initial_dictionary {'b': 2, 'd': 2, 'c': 3, 'a': 1}
resultant key {'d', 'b'}