How to reverse a dictionary with repeated values as a set
Question:
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:
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'}}
Answers:
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))
Your output is comprised of a mixture of value types – i.e., string and set.
A better model would be to use consistent types. In this case, all sets. Then:
d = {'a': 1, 'b': 2, 'c': 3, 'd': 3}
e = {}
for k, v in d.items():
e.setdefault(v, set()).add(k)
print(e)
Output:
{1: {'a'}, 2: {'b'}, 3: {'d', 'c'}}
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:
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'}}
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))
Your output is comprised of a mixture of value types – i.e., string and set.
A better model would be to use consistent types. In this case, all sets. Then:
d = {'a': 1, 'b': 2, 'c': 3, 'd': 3}
e = {}
for k, v in d.items():
e.setdefault(v, set()).add(k)
print(e)
Output:
{1: {'a'}, 2: {'b'}, 3: {'d', 'c'}}