Home > Mobile >  For Loop on List of Dictionaries updating all previous values
For Loop on List of Dictionaries updating all previous values

Time:03-10

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

CodePudding user response:

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

CodePudding user response:

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!

  • Related