我有一个字典,每个字母都有两个值。我需要更新第二个值作为传递重复键。 显然,我尝试的并不是很有效。
if value1 not in dict.keys():
dict.update({key:(value1,value2)})
else:
dict.update({key:value1,+1)})
这只返回了一个值为2的1s而不是递增1
答案 0 :(得分:3)
表达式+1
不会增加任何内容,它只是数字1
同时避免使用dict
作为名称,因为它是Python built-in
尝试更像这样构建代码:
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
可能有更短或更聪明的方法,例如使用运算符+=
,但为了清楚起见,编写了此代码段