1. 简单调换键值对:
{value: key for key, value in dictionary.items()}
2.调换后存在多个键,不能使键值对一一对应:
eg:fooddic = {"apple":"fruit","peach":"fruit","orange":"fruit","tomato":"vegetable","potato":"vegetable"}
A.
#使用标准库中的 defaultdict 模块中有一个数据结构 collections
from collections import defaultdict
d=defaultdict(list)#该数据结构
for k,v in fooddic.items():
d[v] .append(k)
print(d)
B.
#不使用collections,交换字典的键值对,将相同的键对应的值保留在一个列表中
d = {}
for k, v in fooddic.items():
if v not in d.keys():
d[v] = [k]
else:
d[v].append(k)
print(d)