首页 > 解决方案 > 更新列表的元素,其中列表是字典中的值

问题描述

当我尝试更新列表的元素时,其中列表是字典中的值,它会更新字典中每个列表中该索引处的所有值。

示例代码:

dit = {}
d = {}
ls = ['hhh','ew']
a = "hhh"
b = "ew"
j = 3
dit[a] = [1,2,3,4]
dit[b] = [5,6,7,8]
const = [0,2,3,4]
d = dict.fromkeys(dit.keys() ,const)
print(d)
for i in ls:
    print(i)
    d[i][0] = max(d[i][0], j) 
    print(d)
    j += 1

我得到的输出是:

{'hhh': [0, 2, 3, 4], 'ew': [0, 2, 3, 4]}
hhh
{'hhh': [3, 2, 3, 4], 'ew': [3, 2, 3, 4]}
ew
{'hhh': [4, 2, 3, 4], 'ew': [4, 2, 3, 4]}

所需的输出是:

{'hhh': [0, 2, 3, 4], 'ew': [0, 2, 3, 4]}
hhh
{'hhh': [3, 2, 3, 4], 'ew': [0, 2, 3, 4]}
ew
{'hhh': [3, 2, 3, 4], 'ew': [4, 2, 3, 4]}

标签: pythonpython-3.xlistdictionarykey-value

解决方案


发生这种情况是因为您在每个 dict 元素上分配了 const 本身。当您更新此列表时,它将更新其所有出现。在您的代码中更改它,它将起作用:

d = dict.fromkeys(dit.keys() ,const)

d = {i:const.copy() for i in dit.keys()}

推荐阅读