首页 > 解决方案 > 修改字典中的值,添加数量

问题描述

代码

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: 412000: 2

标签: pythondictionary

解决方案


if length in dict:
    dict[length] += amount
else:
    dict[length] = amount

将新添加amount到 dict 条目length是否存在,amount如果它不存在则将其设置为。


推荐阅读