'Best way to add to a value in a dictionary?
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
Solution 1:[1]
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.")
Solution 2:[2]
bank['John'] += 45
You can also use this to simply add another key and value, without using addition.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | EgeO |
| Solution 2 | ouflak |
