簡體   English   中英

添加到字典中的值的最佳方法?

[英]Best way to add to a value in a dictionary?

我對銀行系統的代碼有疑問。 我有一個名為“bank”的列表,其中所有鍵值對的格式都是 name:amount 即。 (約翰:115.6,卡拉:40,山姆:67)。 我希望能夠收取“存款”並將其添加到給定對的總價值中,因此:約翰:115.6 + 45 的存款使約翰:160.6。 那么獲取值和輸入量之和並更新字典的最佳方法是什么?

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

嘗試這個

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.")
bank['John'] += 45

您還可以使用它來簡單地添加另一個鍵和值,而無需使用加法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM