smarter "reverse" of a dictionary in python (acc for some of values being the same)?
- by mrkafk
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?