Reputation: 11
Is there a way to group several keys which points to the same value in a dictionary?
Upvotes: 1
Views: 103
Reputation: 123423
Not exactly sure you want the result structured, but here's one guess:
from collections import defaultdict
mydict = {'a': 1, 'b': 2, 'c': 3, 'd': 2, 'e': 4, 'f': 2, 'g': 4}
tempdict = defaultdict(list)
for k,v in mydict.iteritems():
tempdict[v].append(k)
groupedkeysdict = {}
for k,v in tempdict.iteritems():
groupedkeysdict[tuple(v) if len(v)>1 else v[0]] = k
print groupedkeysdict
# {'a': 1, 'c': 3, ('e', 'g'): 4, ('b', 'd', 'f'): 2}
Upvotes: 2
Reputation: 304137
from collections import defaultdict
newdict = defaultdict(list)
for k,v in originaldict.items():
newdict[v].append(k)
Upvotes: 3