fooddic = {"apple":"fruit","peach":"fruit","orange":"fruit","tomato":"vegetable","potato":"vegetable"}
#使用函数式表达式
#当字典中有两个相同的键时此方法失败
{value: key for key, value in fooddic.items()}
#使用标准库中的 defaultdict 模块中有一个数据结构 collections
from collections import defaultdict
d=defaultdict(list)#该数据结构为字典,且字典中的值的类型是列表
for k,v in fooddic.items():
d[v] .append(k)
d
#不使用collections,交换字典的键值对,将相同的键对应的值保留在一个列表中
d = {}
for k, v in fooddic.items():
if v not in d.keys():
d[v] = [k]
else:
d[v].append(k)
d