【问题标题】:Update an element of a list, where list is a value in dictionary更新列表的元素,其中列表是字典中的值
【发布时间】:2020-09-25 06:40:37
【问题描述】:

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

示例代码:

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]}

【问题讨论】:

    标签: python python-3.x list dictionary key-value


    【解决方案1】:

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

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

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

    【讨论】:

    • 我改了,请重试。可能是相同的逻辑(它只是对所有键使用了 const.copy() 并将它们全部更新)
    • 是的,您的原始版本对原始问题有一个变体。新版本现在可以使用了。
    猜你喜欢
    • 2022-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多