Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to reverse a dictionary with repeated values as a set

I’ve tried flip my dict. If some keys have the same value the flipped dict key should be a set()

d = {'a': 1, 'b': 2, 'c': 3, 'd': 3}

output should be:

{1: 'a', 2: 'b', 3: {'c', 'd'}}

I’ve tried that:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

d = {'a': 1, 'b': 2, 'c': 3, 'd': 3}
rev_dict = {}
for k, v in d.items():
    rev_dict.setdefault(v, set()).add(k)
print(rev_dict)

But I got that:

{1: {'a'}, 2: {'b'}, 3: {'c', 'd'}}

>Solution :

just create a new dictionary

newdict = {}
for key, val in d.items():
   if val not in newdict:
        newdict[val] = key
   else:
        newdict[val] = set((*newdict[val], key))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading