Reverse / invert a dictionary mapping

前端 未结 26 2211
一整个雨季
一整个雨季 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 11:56

    If the values in my_map aren't unique:

    inv_map = {}
    for k, v in my_map.iteritems():
        inv_map[v] = inv_map.get(v, []) + [k]
    

提交回复
热议问题