Reverse / invert a dictionary mapping

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

    A lambda solution for current python 3.x versions:

    d1 = dict(alice='apples', bob='bananas')
    d2 = dict(map(lambda key: (d1[key], key), d1.keys()))
    print(d2)
    

    Result:

    {'apples': 'alice', 'bananas': 'bob'}
    

    This solution does not check for duplicates.

    Some remarks:

    • The lambda construct can access d1 from the outer scope, so we only pass in the current key. It returns a tuple.
    • The dict() constructor accepts a list of tuples. It also accepts the result of a map, so we can skip the conversion to a list.
    • This solution has no explicit for loop. It also avoids using a list comprehension for those who are bad at math ;-)

提交回复
热议问题