首页 > 解决方案 > 通过知道值来增加键 - python字典

问题描述

我需要编写一个代码,每当有人购买产品时,需求字典中的键就会增加 1。我不知道如何通过知道值来增加字典中的键。

这是我尝试过的:

demand = {"bread":0,"butter":0,"cheese":0, "water":0,"ice cream":0}
# bread is the value and 0 is the key, which I want to increase every time

def bill(buy_lst):
    for item in buy_lst:
        demand[demand.get(item)] += 1

当我运行它说:

demand[demand.get(item)] += 1
KeyError: 0

谢谢!

标签: python

解决方案


你的问题真的很简单。您只需*在函数参数前面添加运算符buy_lst,这样您就可以拥有*buylst. 请参阅以下代码:

demand = {"bread":0,"butter":0,"cheese":0, "water":0,"ice cream":0}
# bread is the value and 0 is the key, which I want to increase every time

def bill(*buy_lst):  # see this line
    for item in buy_lst:
        demand[item] += 1  # see this line

bill("bread", "cheese") # The client buys the products `bread` and `cheese`
print(demand)
bill("bread", "cheese", "water", "butter")
print(demand)

输出

{'bread': 1, 'butter': 0, 'cheese': 1, 'water': 0, 'ice cream': 0}
{'bread': 2, 'butter': 1, 'cheese': 2, 'water': 1, 'ice cream': 0}

推荐阅读