SoFunction
Updated on 2024-10-30

Solve python adding dictionary to list overwritten by last one

As shown below:

>>> item={} ; items=[]  # Declare a dictionary and a list. The dictionary is used to add to the list.
>>> item['index']=1    # Assigning a value to a dictionary
>>> (item)
>>> items
[{'index': 1}]      # Add to the list inside the composite expectation
>>> item['index']=2    # Now modify the dictionary
>>> item
{'index': 2}       #Modify successfully
>>> (item)  # Add the modified new dictionary to the list
>>> items         # As expected it should be [{'index': 1}, {'index': 2}]
[{'index': 2}, {'index': 2}]
# Find out why:
>>> id(item),id(items[0]),id(items[1])
(3083974692L, 3083974692L, 3083974692L)

can be seenitem,items[0],items[1]both point to the same object,It's actually the list being added multiple times(quote)same dictionary。

A solution:

>>> items=[]
>>> for i in range(3):
...   item={}     # Redeclare a new dictionary every time
...   item['index']=i
...   (item)
...   id(item)
... 
3084185084L
3084183588L
3084218956L
>>> items
[{'index': 0}, {'index': 1}, {'index': 2}]
>>>

The above article to solve the problem of python to add a dictionary to the list is covered by the last is all that I have shared with you, I hope to give you a reference, and I hope that you will support me more.