【问题标题】:Modify values in dictionary, adding amount修改字典中的值,添加数量
【发布时间】:2018-05-30 14:05:16
【问题描述】:

代码

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

【问题讨论】:

  • if length in dict?

标签: python dictionary


【解决方案1】:
if length in dict:
    dict[length] += amount
else:
    dict[length] = amount

将新的amount 添加到length 的dict 条目(如果它存在),如果它还不存在,则将它设置为amount

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-13
    • 2020-11-20
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    相关资源
    最近更新 更多