Home > Software engineering >  Best way to add to a value in a dictionary?
Best way to add to a value in a dictionary?

Time:02-22

Im having an issue with code for a banking system. I have a list called "bank" where all of the key value pairs are in the format name:amount ie. (John : 115.6 , Carla : 40 , Sam :67). I want to be able to take a "deposit" and add it to the total value in a given pair so: John : 115.6 a deposit of 45 makes John : 160.6 . So whats the best way to get the sum of a value and input amount and update the dictionary?

if username in log_in:
    if log_in.values() == True:
        print(username)
    if amount < 0 and bank.values() - amount < 0:
        return False
    if amount > 0:
        bank_update = bank.values()   amount
        bank.update(bank_update)
    return True
else:
    return False

CodePudding user response:

Try this

bank = {"John" : 115.6, "Carla" : 40, "Sam" : 67}

username = input()
amount = int(input())

if amount > 0:
    try:
        bank[username]  = amount
        print(bank)
    except:
        print("There is no one with this username in bank dictionary.")

CodePudding user response:

bank['John']  = 45

You can also use this to simply add another key and value, without using addition.

  • Related