我有一个字典,其中的键每个都有两个值。我需要更新第二个值作为传递重复的键。 显然我正在尝试的方法没有成功。
<小时/>if value1 not in dict.keys():
dict.update({key:(value1,value2)})
else:
dict.update({key:value1,+1)})
这只是返回一个值为 2 的字典,其中 1 秒而不是递增 1
最佳答案
表达式+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
可能有更短或更聪明的方法来做到这一点,例如使用运算符 +=
,但编写此代码片段是为了清楚起见
关于Python:用元组值更新字典键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34034388/