Reverse / invert a dictionary mapping

前端 未结 26 2230
一整个雨季
一整个雨季 2020-11-21 11:47

Given a dictionary like so:

my_map = {\'a\': 1, \'b\': 2}

How can one invert this map to get:

inv_map = {1: \'a\', 2: \'b\'         


        
26条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-21 12:04

    We can also reverse a dictionary with duplicate keys using defaultdict:

    from collections import Counter, defaultdict
    
    def invert_dict(d):
        d_inv = defaultdict(list)
        for k, v in d.items():
            d_inv[v].append(k)
        return d_inv
    
    text = 'aaa bbb ccc ffffd aaa bbb ccc aaa' 
    c = Counter(text.split()) # Counter({'aaa': 3, 'bbb': 2, 'ccc': 2, 'ffffd': 1})
    dict(invert_dict(c)) # {1: ['ffffd'], 2: ['bbb', 'ccc'], 3: ['aaa']}  
    

    See here:

    This technique is simpler and faster than an equivalent technique using dict.setdefault().

提交回复
热议问题