Python | Find keys with duplicate values in dictionary

Given a dictionary, the duty is to search out keys with duplicate values. Let’s talk about a couple of strategies for a similar.

Method #1: Using Naive method
In this methodology first, we convert dictionary values to keys with the inverse mapping after which discover the duplicate keys

  

ini_dict =

  

print(“initial_dictionary”, str(ini_dict))

  

rev_dict =

  

for key, worth in ini_dict.objects():

    rev_dict.setdefault(worth, set()).add(key)

      

outcome = [key for key, values in rev_dict.objects()

                              if len(values) > 1]

  

print(“duplicate values”, str(outcome))

Output:

initial_dictionary
duplicate values [2]

 
Method #2: Using flipping dictionary

  

ini_dict =

  

print(“initial_dictionary”, str(ini_dict))

  

flipped =

  

for key, worth in ini_dict.objects():

    if worth not in flipped:

        flipped[value] = [key]

    else:

        flipped[value].append(key)

  

print(“final_dictionary”, str(flipped))

Output:

initial_dictionary ‘a’: 1, ‘c’: three, ‘d’: 2, ‘b’: 2
final_dictionary

 
Method #three: Using chain and set

Suppose you must discover keys having duplicate values.

from itertools import chain

  

ini_dict =

  

print(“initial_dictionary”, str(ini_dict))

  

rev_dict =

for key, worth in ini_dict.objects():

    rev_dict.setdefault(worth, set()).add(key)

  

  

outcome = set(chain.from_iterable(

         values for key, values in rev_dict.objects()

         if len(values) > 1))

  

print(“resultant key”, str(outcome))

Output:

initial_dictionary ‘b’: 2, ‘d’: 2, ‘c’: three, ‘a’: 1
resultant key

Programming freak_tech Enthusiast and have curiosity in studying new upcoming applied sciences.

If you want GeeksforGeeks and wish to contribute, you may also write an article utilizing contribute.geeksforgeeks.org or mail your article to [email protected] See your article showing on the GeeksforGeeks predominant web page and assist different Geeks.

Please Improve this text in the event you discover something incorrect by clicking on the “Improve Article” button under.

Article Tags :

thumb_up
Be the First to upvote.

Please write to us at [email protected] to report any situation with the above content material.

Post navigation

Previous

first_page Python | Combine two lists by sustaining duplicates in first record

Share this put up!