我需要编写一个代码,每次有人购买产品时,需求字典中的密钥就会增加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
谢谢!
答案 0 :(得分:0)
您似乎误解了key
和value
,在您的情况下,字符串为keys
,其数量为value
demand = {"bread": 0, "butter": 0, "cheese": 0, "water": 0, "ice cream": 0}
所以,您想要的是给定键的增加值
buy_lst[item] += 1
要使用它,您需要向用户询问一种产品,例如
def bill(buy_lst):
item = None
while not item:
item = input("Please select in " + str(list(buy_lst.keys())))
item = item if item in buy_lst else None
buy_lst[item] += 1
if __name__ == '__main__':
demand = {"bread": 0, "butter": 0, "cheese": 0, "water": 0, "ice cream": 0}
bill(demand)
print(demand)
答案 1 :(得分:0)
您的问题是您如何添加字典。请注意以下几点:
demand = {"bread": 0, "butter": 0, "cheese": 0, "water": 0, "ice cream": 0}
buy_lst = ["bread", "butter", "bread"]
def bill(buy_lst):
for item in buy_lst:
print(demand.get(item))
#demand[demand.get(item)] += 1
bill(buy_lst)
这将输出:
0
0
0
因此,换句话说,就是您的:
demand[demand.get(item)] += 1
您正在做
demand[0] += 1
哪个将返回错误:
Traceback (most recent call last):
File "/Users/felipefaria/Desktop/test/main.py", line 11, in <module>
bill(buy_lst)
File "/Users/felipefaria/Desktop/test/main.py", line 8, in bill
demand[demand.get(item)] += 1
KeyError: 0
相反,您应该仅在括号内引用项目本身,如下所示:
demand = {"bread": 0, "butter": 0, "cheese": 0, "water": 0, "ice cream": 0}
buy_lst = ["bread", "butter", "bread"]
def bill(buy_lst):
for item in buy_lst:
demand[item] += 1
bill(buy_lst)
print(demand)
哪个会输出:
{'bread': 2, 'butter': 1, 'cheese': 0, 'water': 0, 'ice cream': 0}
答案 2 :(得分:0)
我认为您试图表达的意思是“增加我所知道的钥匙的价值”。因为只有值是整数,所以只有它们可以递增。因此,递增值将是:
demand = {"bread":0,"butter":0,"cheese":0, "water":0,"ice cream":0}
def bill(buy_lst):
for item in buy_lst:
demand[item] += 1
为澄清起见,词典项目的第一部分是key
,第二部分是value
。
答案 3 :(得分:0)
您可能会混淆键和值。在demand
中,键是项目,值是计数。
#!/usr/bin/env python
demand = {"bread":0, "butter":0, "cheese":0, "water":0, "ice cream":0}
def bill(buy_list):
for item in buy_list:
demand[item] += 1
buy_list = ["bread", "water"]
print("Before billing:")
print(demand)
bill(buy_list)
print("After billing")
print(demand)
此打印:
Before billing:
{'bread': 0, 'butter': 0, 'cheese': 0, 'water': 0, 'ice cream': 0}
After billing
{'bread': 1, 'butter': 0, 'cheese': 0, 'water': 1, 'ice cream': 0}
答案 4 :(得分:0)
您的问题确实很简单。您只需要在函数参数*
前面添加运算符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}