Search code examples
pythonlistdictionaryenumerate

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

Solution

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