字典列表上的 For 循环更新所有以前的值

For Loop on List of Dictionaries updating all previous values

我正在尝试将字典的值更新为另一个列表提供的值,但更新也发生在所有以前的值上。

这是我的代码片段:

dict = {'name' : 'shubham', 'age': 23}

listDict = [dict]*5
names = ['sh', 'shu', 'shub', 'shubh', "shubha"]

print(listDict)

for ind, dic in enumerate(listDict):
    listDict[ind]['name'] = names[ind]

print(listDict)

即将输出:

[{'name': 'shubha', 'age': 23},
 {'name': 'shubha', 'age': 23},
 {'name': 'shubha', 'age': 23},
 {'name': 'shubha', 'age': 23},
 {'name': 'shubha', 'age': 23}]

它应该会来 :

[{'name': 'sh', 'age': 23},
 {'name': 'shu', 'age': 23},
 {'name': 'shub', 'age': 23},
 {'name': 'shubh', 'age': 23},
 {'name': 'shubha', 'age': 23}]

当你执行 [dict]*5 操作时,你之后得到的是内存中对同一个字典对象的 5 个引用的列表,因此当你编辑一个时,你实际上是在编辑所有这些。有关此的更多解释,请查看 python 中可变对象和不可变对象之间的区别(这是因为字典是可变的)。

要完成你想要的,你需要明确地复制初始字典。

listDict = [dict.copy() for i in range(5)]

这应该会产生您期望的结果。 (也是一个友好的提示:你应该避免将你的第一本字典命名为 dict:这会掩盖 dict() 函数并且会让人难以阅读!)

如果您像这样创建词典列表:[dict]*5词典将相互链接。

所以我建议你这样做乘法:

dict = {'name' : 'shubham', 'age': 23}

listDict = [ dict.copy() for i in range(5) ]
names = ['sh', 'shu', 'shub', 'shubh', "shubha"]

print(listDict)

for ind, dic in enumerate(listDict):
    listDict[ind]['name'] = names[ind]

print(listDict)

希望我有所帮助!