Reverse / invert a dictionary mapping

前端 未结 26 2234
一整个雨季
一整个雨季 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:59

    This handles non-unique values and retains much of the look of the unique case.

    inv_map = {v:[k for k in my_map if my_map[k] == v] for v in my_map.itervalues()}
    

    For Python 3.x, replace itervalues with values.

提交回复
热议问题