Reverse / invert a dictionary mapping

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

    If the values aren't unique, and you're a little hardcore:

    inv_map = dict(
        (v, [k for (k, xx) in filter(lambda (key, value): value == v, my_map.items())]) 
        for v in set(my_map.values())
    )
    

    Especially for a large dict, note that this solution is far less efficient than the answer Python reverse / invert a mapping because it loops over items() multiple times.

提交回复
热议问题