Reverse / invert a dictionary mapping

前端 未结 26 2213
一整个雨季
一整个雨季 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}
    
    0 讨论(0)
  • 2020-11-21 11:58

    Combination of list and dictionary comprehension. Can handle duplicate keys

    {v:[i for i in d.keys() if d[i] == v ] for k,v in d.items()}
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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 ;-)
    0 讨论(0)
  • 2020-11-21 12:00

    To do this while preserving the type of your mapping (assuming that it is a dict or a dict subclass):

    def inverse_mapping(f):
        return f.__class__(map(reversed, f.items()))
    
    0 讨论(0)
  • 2020-11-21 12:02

    I found that this version is more than 10% faster than the accepted version of a dictionary with 10000 keys.

    d = {i: str(i) for i in range(10000)}
    
    new_d = dict(zip(d.values(), d.keys()))
    
    0 讨论(0)
提交回复
热议问题