修改字典中的值,添加金额

时间:2018-05-30 14:05:17

标签: python dictionary

代码

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

1 个答案:

答案 0 :(得分:1)

if length in dict:
    dict[length] += amount
else:
    dict[length] = amount
如果amount存在,

会将新length添加到dict条目中,如果它尚不存在,则将其设置为amount