Python:用元组值更新字典键

标签 python python-3.x

我有一个字典,其中的键每个都有两个值。我需要更新第二个值作为传递重复的键。 显然我正在尝试的方法没有成功。

<小时/>
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/

相关文章:

python - 按 Enter 键继续。 。 。然后删除语句 (Python)

python - 在 python 3 中遍历枚举时,并非所有元素都出现

python-3.x - Python 中的不相交集实现

python-3.x - AttributeError : module 'tkinter' has no attribute 'TclError' ?的原因是什么

python - Django 如何知道呈现表单字段的顺序?

python - Pandas - 如果满足条件则更新列

python - Berkeley DB是否只支持一种处理器操作

Python - 使用 var 值命名类的实例

Python sqlite3 如果 executemany() 中途遇到完整性错误会怎样?

python - 从 QWebEngineProfile 获取 cookie 作为字典