如何在Python中的字典中添加相似的键及其值?

时间:2020-04-02 03:18:11

标签: python dictionary

我正在编写一个代码,该代码基本上将两个字典中相似项目中的值相加,并打印其余项目。

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)

1 个答案:

答案 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})