python - 修改字典中的值,添加数量
问题描述
代码
dict = {}
flag = True
while True:
length = raw_input('enter length')
amount = raw_input('enter amount')
if (length == 'quit') or (amount == 'quit'):
flag = False
continue
我想添加代码所以
if key in dict:
# previous value + amount
# insert the new value to the key
else:
dict[length] = amount
例如:我的输入是:13000,2
比:12000: 2
再次:13000: 2
所以 dict 将包括13000: 4
和12000: 2
解决方案
if length in dict:
dict[length] += amount
else:
dict[length] = amount
将新添加amount
到 dict 条目length
是否存在,amount
如果它不存在则将其设置为。
推荐阅读
- sql - 如何在PostgreSQL中用800万行数据更新一列表
- google-sheets - 添加到 Excel/Google 表格中的数组
- blockchain - 智能合约在技术上保存在 ETH 区块链中的哪个位置?
- tensorflow - 用于图像分割数据集的 Keras 数据增强管道(具有相同操作的图像和掩码)
- html - 美汤如何根据班级信息找到孙子标签?
- php - 在自定义数组中设置一些 WooCommerce 订单和订单商品数据
- javascript - 从按钮获取值 echo $row
- reporting-services - Microsoft Report Builder 2016 参数的开始日期问题
- mysql - SQL 查询以获取未在产品中注册的客户 ID
- node.js - 快速删除请求甚至不处理请求正文