def revert_dict(d):
rd = {}
for key in d:
val = d[key]
if val in rd:
rd[val].append(key)
else:
rd[val] = [key]
return rd
>>> revert_dict({'srvc3': '1', 'srvc2': '1', 'srvc1': '2'})
{'1': ['srvc3', 'srvc2'], '2': ['srvc1']}
This obviously isn't simple exchange of keys with values: this would overwrite some values (as new keys) which is NOT what I'm after.
If 2 or more values are the same for different keys, keys are supposed to be grouped in a list.
The above function works, but I wonder if there is a smarter / faster way?
That looks pretty good. You could simplify it a little bit by using defaultdict
:
import collections
def revert_dict(d):
rd = collections.defaultdict(list)
for key, value in d.iteritems():
rd[value].append(key)
return rd
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With