简体   繁体   English

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

[英]For Loop on List of Dictionaries updating all previous values

I am trying to update the values of the dictionary as the values provided by another list, but the update is happening to all of the previous values as well.我正在尝试将字典的值更新为另一个列表提供的值,但更新也发生在所有以前的值上。

Here is my code snippet:这是我的代码片段:

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)

Output is coming: Output 来了:

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

It should be coming:它应该来了:

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

When you do the [dict]*5 operation, what you have afterwards is a list of 5 references to the same dictionary object in memory, thus when you edit one you are actually editing all of them.当你执行[dict]*5操作时,你之后得到的是 memory 中对同一个字典 object 的 5 个引用的列表,因此当你编辑一个时,你实际上是在编辑所有这些。 For more explanation of this, look up the difference between Mutable and Immutable objects in python (this occurs because dictionaries are mutable).有关此的更多解释,请查看 python 中可变对象和不可变对象之间的区别(这是因为字典是可变的)。

To accomplish what you want, you need to explicitly make copies of the initial dict.为了完成你想要的,你需要明确地制作初始字典的副本。

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

This should create the result you expect.这应该会产生您期望的结果。 (also friendly tip: your should avoid naming your first dictionary dict : that shadows the dict() function and is confusing to read!) (也是一个友好的提示:你应该避免命名你的第一个字典dict :它掩盖了dict() function 并且阅读起来很混乱!)

If you create a list of dictionaries like this: [dict]*5 the dictionaries will be linked to each other.如果你像这样创建一个字典列表: [dict]*5字典将相互链接。

So I suggest you to do the multiplication this way:所以我建议你用这种方式做乘法:

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)

Hope I helped!希望我有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM