Solve the problem of dictionary writing list in python

When I used the list to write a dictionary today, I found that the contents of the list were all the same dictionary, and it was the last dictionary written.
Example:

a=[]
b={
    
    
    "name":" "
  }
for i in range(4):
    b["name"]=i
    a.append(b)

print(a)

The results of the operation are:

[{
    
    'name': 3}, {
    
    'name': 3}, {
    
    'name': 3}, {
    
    'name': 3}]

???
Shouldn't it be 0, 1, 2, 3? Why are all 3? I found some information and found the problem. The original list uses append to add data to the list instead of writing the complete dictionary data into the list. , But the address where the dictionary data is written, and the above method modifies the data under the memory address, which causes the list to store all the addresses of the same dictionary, and the last one is called from the address when outputting Dictionary

The solution
can use compy() to solve this problem

a=[]
b={
    
    
    "name":" "
  }
for i in range(4):
    b["name"]=i
    a.append(b.copy())

print(a)

Output:

[{
    
    'name': 0}, {
    
    'name': 1}, {
    
    'name': 2}, {
    
    'name': 3}]

Perfect solution!

Guess you like

Origin blog.csdn.net/xinzhilinger/article/details/102771842