Python:使用元组值更新字典键
我有一个字典,每个字典都有两个值。我需要更新第二个值作为传递重复键。 很明显,我所尝试的是行不通的Python:使用元组值更新字典键,python,python-3.x,Python,Python 3.x,我有一个字典,每个字典都有两个值。我需要更新第二个值作为传递重复键。 很明显,我所尝试的是行不通的 这只是返回了一个用1s表示值2的措辞,而不是递增1表达式+1没有递增任何内容,它只是数字1 同时避免使用dict作为名称,因为它是一个 请尝试按以下方式构建代码: my_dict = {} # some dict my_key = # something if my_key not in my_dict: new_value = # some new value here my
这只是返回了一个用1s表示值2的措辞,而不是递增1表达式
+1
没有递增任何内容,它只是数字1
同时避免使用dict
作为名称,因为它是一个
请尝试按以下方式构建代码:
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
可能有更简短或更聪明的方法,例如使用操作符
+=
,但这段代码是为了清晰起见编写的您的问题不太清楚您的预期结果是什么-当值1
已经是dict
中的一个键时会发生什么?值1我想保持不变。我只想增加值2。Value2只是一个计数器,用于在密钥已经存在时,将密钥与字典进行比较的次数。如果我能够抓取密钥的元组,则会进行检查。我能增加第二个值,然后更新字典吗?是的,我刚刚读了你在问题中的评论,请看增加元组中第二个元素的示例:)似乎是一个愚蠢的问题,我应该知道答案,但我如何接受答案…没关系。
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