#第一步,建立字典dic_menu:
dic_menu={"蔬菜":{"青菜":"绿色","胡萝卜":"橙色","茄子":"紫色","毛豆":"绿色"}, "水果":{"山竹":"紫色","香蕉":"黄色","橙子":"橙色","草莓":"红色"}, "饮料":{"椰子汁":"白色","西瓜汁":"红色","玉米汁":"黄色","葡萄汁":"紫色"}} b={} for i in dic_menu.values(): #循环用集合i承接dic_menu键值对中的值(values),结果如下 for j in i.values(): #再一次循环用j承接集合i中键值对中的值,j即为颜色 if j not in b: #if判断颜色是否有重复, b[j]=1 #若无重复,则直接赋值为1,b[j]即为颜色出现的数量 else: #若有重复,则每重复一次,b[j]的值+1 b[j] += 1
print(b) #此处b的结果可打可不打,结果如下,不是最后结果
for i,j in b.items(): #循环在集合b中找到对应的键值对
print('{}的食物有{}个' .format(i,j)) #打印输出最后结果
第一次for循环的结果如下:
打印b的结果如下:
{'绿色': 2, '橙色': 2, '紫色': 3, '黄色': 2, '红色': 2, '白色': 1}
最后结果如下:
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
第二种方法:
dic_menu={"蔬菜":{"青菜":"绿色","胡萝卜":"橙色","茄子":"紫色","毛豆":"绿色"}, "水果":{"山竹":"紫色","香蕉":"黄色","橙子":"橙色","草莓":"红色"}, "饮料":{"椰子汁":"白色","西瓜汁":"红色","玉米汁":"黄色","葡萄汁":"紫色"}} dic_color = {} for k, v in dic_menu.items(): for key, value in v.items(): dic_color[value] = dic_color.get(value, 0) + 1 print(dic_color)
标签:pathon,color,menu,dic,紫色,键值,橙色 From: https://www.cnblogs.com/Argitacos/p/17385761.html