python字典互换键值
循环
dic = {'a':1, 'b':2, 'c':3}
dic_new = {}
for key, val in dic.items():
dic_new[val] = key
print(dic_new)
# {1: 'a', 2: 'b', 3: 'c'}
zip
dic = {'a':1, 'b':2, 'c':3}
dic_new = dict(zip(dic.values(), dic.keys()))
print(dic_new)
# {1: 'a', 2: 'b', 3: 'c'}
列表生成器
dic_new = dict([val, key] for key, val in dic.items())
print(dic_new)
# {1: 'a', 2: 'b', 3: 'c'}