smarter "reverse" of a dictionary in python (acc for some of values being the same)?

Posted by mrkafk on Stack Overflow See other posts from Stack Overflow or by mrkafk
Published on 2011-01-13T21:12:32Z Indexed on 2011/01/13 21:53 UTC
Read the original article Hit count: 178

Filed under:
|
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?

© Stack Overflow or respective owner

Related posts about python

Related posts about dictionary