theVoid theVoid - 6 months ago 10
Python Question

Initialization of a list of dictionaries

I want to take input from the user and initialize a list of dictionaries.
I have the following block which works fine.

people = []

for p in range(3):
cell = {"name": "","age" : 0, "education" : "","height" : 0}
cell["name"] = input("name:")
cell["age"] = int(input("age:"))
cell["education"] = input("education:")
cell["height"] = float(input("height:"))
people.append(cell)


The problem I have is why the following block does not work for me.

people = []

cell = {"name": "","age" : 0, "education" : "","height" : 0}
for p in range(0,3):
cell["name"] = input("name:")
cell["age"] = int(input("age:"))
cell["education"] = input("education:")
cell["height"] = float(input("height:"))
people.append(cell)


I do not understand why at the end of the iteration I have the list initialized with the latest input all the 3 times, I mean when I use this line:

cell["name"] = input("name:")


shouldn't the previous value been replaced with the new one?

Answer

The important part is this line:

cell = {"name": "","age" : 0, "education" : "","height" : 0}

here you create a dictionary and save a reference to it under cell

If you do this before the loop (like in your second example) you have only created one dictionary and appended it to the list three times. So if you change anything inside of any dictionary, your changes will show up at all indices of the list (since they all point to the same dictionary)

However, if you run the line inside of your loop you actually create three different dictionaries, which is essentially what you want here. This is why your first example works and your second one doesn't.

Comments