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'}
posted @ 2020-04-21 09:30  苟不理包子  阅读(1075)  评论(0编辑  收藏  举报