【发布时间】:2019-07-16 12:24:25
【问题描述】:
我是 Python 新手,所以请放轻松。我正在使用字典为一个键存储多个值,但是,当我尝试更新值时遇到问题。这是我设置字典的方法;首先,我使用setdefault() 编写第一个值:
dictionary.setdefault(id.ID, []).append(id.enterTime)
dictionary.setdefault(id.ID, []).append(id.duration)
dictionary.setdefault(id.ID, []).append(id.enter)
dictionary.setdefault(id.ID, []).append(id.exit)
dictionary.setdefault(id.ID, []).append(id.standing)
dictionary.setdefault(id.ID, []).append(id.sitting)
为了解释起见,假设它在打印时产生以下输出:
{0: [5, 120, 0, 0, 0, 0]}
当 id.enter 实例变量更改时,我使用以下代码更新字典,只需删除原始值并将新值附加到字典:
dictionary[id.ID].remove(id.enter)
dictionary[id.ID].insert(2, id.enter)
字典打印如下:
{0: [5, 120, 1, 0, 0, 0]}
稍后在程序中,实例变量 id.exit 变为 1。我尝试在字典中将退出值从 0 更新为 1 后更改如下:
dictionary[id.ID].remove(id.exit)
dictionary[id.ID].insert(3, id.exit)
我知道这样做的方法很糟糕,但我认为这是更新值的最简单方法。当我这样做时,会出现问题,因为它将id.enter 更改回其原始值但更新id.exit:
{0: [5, 120, 0, 1, 0, 0]}
有人知道为什么会这样吗?谢谢。
【问题讨论】:
-
为什么不在字典中存储对象?修改值会更容易。另请参阅 python 3 中的 dataclasses。
-
remove()删除列表中与参数匹配的 first 值。您传递了id.exit的new 值,恰好等于id.enter的old 值(存储在索引2,而不是3)。当从列表中删除一个元素时,所有存储在它之后的元素都会向后移动 1 个空格,因此id.enter的新值变为id.exit的 旧 值(原为 0)。 -
@meowgoesthedog 谢谢你的信息。这种修改列表的方法会奏效吗,或者这是一种天真的方式来改变它?
-
@cz46 依赖存储顺序是一种糟糕的方法 - 直接存储
id对象或使用字典 /namedtuple代替。
标签: python dictionary key-value