![](/img/trans.png)
[英]Accessing indexed element of a list, where the list is a value of a python dictionary
[英]Update an element of a list, where list is a value in dictionary
当我尝试更新列表的元素时,其中 list 是字典中的一个值,它会更新字典中每个列表中该索引处的所有值。
示例代码:
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]}
发生这种情况是因为您在每个 dict 元素上分配了 const 本身。 当您更新此列表时,它将更新其所有出现。 在您的代码中更改它,它将起作用:
d = dict.fromkeys(dit.keys() ,const)
到
d = {i:const.copy() for i in dit.keys()}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.