Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 286
mrkafk Avatar asked Jan 13 '11 21:01

mrkafk


1 Answers

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
like image 189
John Kugelman Avatar answered Oct 16 '22 20:10

John Kugelman