簡體   English   中英

Python:使用元組值更新字典鍵

[英]Python: update dictionary key with tuple values

我有一個字典,每個字母都有兩個值。 我需要更新第二個值作為傳遞重復鍵。 顯然我正在努力的是沒有成功。


if value1 not in dict.keys():
    dict.update({key:(value1,value2)})
else:
    dict.update({key:value1,+1)})

這只是返回一個值為2的1s而不是遞增1

表達式+1不會增加任何內容,它只是數字1

還要避免使用dict作為名稱,因為它是內置Python

嘗試更像這樣構建代碼:

my_dict = {} # some dict
my_key = # something

if my_key not in my_dict:
    new_value = # some new value here
    my_dict[my_key] = new_value
else:
    # First calculate what should be the new value

    # Here I'm doing a trivial new_value = old_value + 1, no tuples
    new_value = my_dict[my_key] + 1
    my_dict[my_key] = new_value

    # For tuples you can e.g. increment the second element only
    # Of course assuming you have at least 2 elements,
    # or old_value[0] and old_value[1] will fail
    old_value = my_dict[my_key] # this is a tuple
    new_value = old_value[0], old_value[1] + 1
    my_dict[my_key] = new_value 

可能有更短或更聰明的方法,例如使用運算符+= ,但為了清楚起見,編寫了此代碼段

暫無
暫無

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

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