-4

Code

dict = {}
flag = True
while True:  
    length = raw_input('enter length')
    amount = raw_input('enter amount')
    if (length == 'quit') or (amount == 'quit'):
        flag = False
        continue

I want to add code so

if key in dict:
     # previous value + amount
     # insert the new value to the key
else: 
     dict[length] = amount

for example: my inputs are: 13000,2 than: 12000: 2 and again: 13000: 2

so dict will include 13000: 4 and 12000: 2

1

1 Answer 1

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

will add the new amount to dict entry for length if it exists and sets it to amount if it doesn't exist yet.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.