繁体   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