Reverse / invert a dictionary mapping

前端 未结 26 3079
一整个雨季
一整个雨季 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: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()))
    

提交回复
热议问题