python - 通过知道值来增加键 - 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
谢谢!
解决方案
你的问题真的很简单。您只需*
在函数参数前面添加运算符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}
推荐阅读
- c# - Unity 2D 画布缩放器
- python - Pandas 系列 str 拆分方法因负前瞻而中断
- android - 在 Android Management API 中扫描 QR 以注册 Android 设备后,如何使设备连接到 wifi?
- c# - 当我在 Visual Studio 中单击发布时如何知道发布完整命令
- java - 如何在 Cucumber 框架中实现 Dev 和 Staging 的代码
- swift - SwiftUI 构建列表和导航 - 遵循教程时无法渲染画布 - 更新时间超过 5 秒/崩溃
- c# - 升级项目 Unity 2019 -> 2020
- prolog - Prolog中的Powerset oa set(list)
- javascript - fullcalendar.io 和 mootools 冲突
- java - 如何将带有索引和键的数组放入请求的键中