Invert keys and values of the original dictionary

后端 未结 3 394
别那么骄傲
别那么骄傲 2020-12-18 01:11

For example, I call this function by passing a dictionary as parameter:

>>> inv_map({\'a\':1, \'b\':2, \'c\':3, \'d\':2})
{1: [\'a\'], 2: [\'b\', \'         


        
3条回答
  •  太阳男子
    2020-12-18 01:35

    You can probably use defaultdict or setdefault here.

    def invertDictionary(orig_dict):
        result = {} # or change to defaultdict(list)
        for k, v in orig_dict.iteritems():
            result.setdefault(v, []).append(k)
    

提交回复
热议问题