简体   繁体   中英

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:

[{'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. For more explanation of this, look up the difference between Mutable and Immutable objects in python (this occurs because dictionaries are mutable).

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!)

If you create a list of dictionaries like this: [dict]*5 the dictionaries will be linked to each other.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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