给列表里添加字典时被最后一个覆盖

>>> item={} ; items=[]    #先声明一个字典和一个列表,字典用来添加到列表里面
>>> item['index']=1       #给字典赋值
>>> items.append(item)
>>> items
[{'index': 1}]            #添加到列表里面复合预期
>>> item['index']=2       #现在修改字典
>>> item
{'index': 2}              #修改成功
>>> items.append(item)    #将修改后的新字典添加到列表
>>> items                 #按预期应该是[{'index': 1}, {'index': 2}]
[{'index': 2}, {'index': 2}]
#找一下原因:
>>> id(item),id(items[0]),id(items[1])
(3083974692L, 3083974692L, 3083974692L)
可以看到item,items[0],items[1]都指向同一个对象,实际上是列表在多次添加(引用)同一个字典。

一种解决的办法:

>>> items=[]
>>> for i in range(3):
...     item={}         #每次都重新声明一个新字典
...     item['index']=i
...     items.append(item)
...     id(item)
... 
3084185084L
3084183588L
3084218956L
>>> items
[{'index': 0}, {'index': 1}, {'index': 2}]
>>>
文章出处:http://www.cnblogs.com/aaron-agu/ 只有毅力和决心才能使人真正具有价值!
原文地址:https://www.cnblogs.com/aaron-agu/p/5825519.html