0

I'm trying to create a list that has 10 dictionaries (each with the same key-value pair) within python, but I've realized that the way dictionaries in lists are updated differ based on how the list is initialized, is anyone able to explain why?

00 person = {'name':'', 'phone':0}
01 
02 # The following three lines result in a different way the dictionary is updated
03 dataStructure = [{'name':'', 'phone':0} for i in range(10)]
04 # dataStructure = [{'name':'', 'phone':0}] * 10
05 # dataStructure = [person  for i in range(10)]
06 
07 dataStructure[0]['name'] = 'hi'
08 print(dataStructure)

For the code above, only line 03 would result in dataStructure[0]['name'] = 'hi' only updating the first dict in list.
Lines 04 and 05 results in all elements in the dictionary being updated.

I'm not that great at python, any help would be appreciated! Thanks :D

Daren Tan
  • 33
  • 6

1 Answers1

1

This has to do with how referencing works in python. Basically everything is an object in python, so unless you are initializing a new object (like working with "primitives" or calling constructors), Python will reference the object itself.

In your first example, you are creating a new dictionary 10 times, which is why you are able to update them separately.

In your second example, you create the dictionary object, then "duplicate" it 10 times, so each of those instances is just referencing the first object.

In your third example, person is already created, so each of the elements of the list are just referencing the person object.

shadow-kris
  • 196
  • 5