我正在编写一个代码,该代码基本上将两个字典中相似项目中的值相加,并打印其余项目。
food = ["cheese pizza", "quiche","morning bun","gummy bear","tea cake"]
bakery_stock = {
"almond croissant" : 12,
"toffee cookie": 3,
"morning bun": 1,
"chocolate chunk cookie": 9,
"tea cake": 25
}
new_di = dict.fromkeys(food, 1)
if new_di in bakery_stock:
bakery_stock.update(new_di)
print(bakery_stock)
答案 0 :(得分:1)
>>> from collections import Counter
>>> food = ["cheese pizza", "quiche","morning bun","gummy bear","tea cake"]
>>> bakery_stock = {
... "almond croissant" : 12,
... "toffee cookie": 3,
... "morning bun": 1,
... "chocolate chunk cookie": 9,
... "tea cake": 25
... }
>>> new_di = dict.fromkeys(food, 1)
>>> Counter(bakery_stock) + Counter(new_di)
Counter({'tea cake': 26, 'almond croissant': 12, 'chocolate chunk cookie': 9, 'toffee cookie': 3, 'morning bun': 2, 'cheese pizza': 1, 'quiche': 1, 'gummy bear': 1})