Reverse / invert a dictionary mapping

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

    Try this:

    inv_map = dict(zip(my_map.values(), my_map.keys()))
    

    (Note that the Python docs on dictionary views explicitly guarantee that .keys() and .values() have their elements in the same order, which allows the approach above to work.)

    Alternatively:

    inv_map = dict((my_map[k], k) for k in my_map)
    

    or using python 3.0's dict comprehensions

    inv_map = {my_map[k] : k for k in my_map}
    

提交回复
热议问题