给定一本这样的字典:

my_map = {'a': 1, 'b': 2}

如何将此映射颠倒得到:

inv_map = {1: 'a', 2: 'b'}

当前回答

我会在python2中这样做。

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

其他回答

另一种更实用的方法是:

my_map = { 'a': 1, 'b':2 }
dict(map(reversed, my_map.items()))

试试python 2.7/3.x

inv_map={};
for i in my_map:
    inv_map[my_map[i]]=i    
print inv_map

我会在python2中这样做。

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

我发现这个版本比10000个键的字典的公认版本快10%以上。

d = {i: str(i) for i in range(10000)}

new_d = dict(zip(d.values(), d.keys()))

我在循环'for'和方法'.get()'的帮助下写了这篇文章,我把字典的'map'名字改为'map1',因为'map'是一个函数。

def dict_invert(map1):
    inv_map = {} # new dictionary
    for key in map1.keys():
        inv_map[map1.get(key)] = key
    return inv_map