将字典附加到循环Python中的列表中

时间:2014-05-18 16:20:25

标签: python list dictionary append

我是一名基本的python程序员,所以希望我的问题的答案很容易。 我正在尝试拿一本字典并将其附加到列表中。然后字典更改值,然后在循环中再次附加。似乎每次执行此操作时,列表中的所有字典都会更改其值以匹配刚刚附加的字典。 例如:

>>> dict = {}
>>> list = []
>>> for x in range(0,100):
...     dict[1] = x
...     list.append(dict)
... 
>>> print list

我认为结果将是[{1:1}, {1:2}, {1:3}... {1:98}, {1:99}],但我得到了:

[{1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}]

非常感谢任何帮助。

5 个答案:

答案 0 :(得分:47)

您需要附加副本,否则您只是一遍又一遍地添加对同一字典的引用:

yourlist.append(yourdict.copy())

我使用yourdictyourlist代替dictlist;你不想掩盖内置类型。

答案 1 :(得分:4)

在循环外创建adict字典时,您将相同的字典附加到alist列表中。这意味着所有副本都指向同一个字典,并且每次都获得最后一个值{1:99}。只需在循环中创建每个字典,现在就有100个不同的字典。

alist = []
for x in range(100):
    adict = {1:x}
    alist.append(adict)
print(alist)

答案 2 :(得分:3)

dict = {}放入循环中。

>>> dict = {}
>>> list = []
>>> for x in range(0, 100):
       dict[1] = x
       list.append(dict)
       dict = {}

>>> print list

答案 3 :(得分:2)

您还可以使用zip和列表理解来完成您的需要。

如果您希望dict值从一次使用开始range(1,100)

l = [dict(zip([1],[x])) for x in range(1,100)]

答案 4 :(得分:0)

假设d是您的字典。在这里,如果您进行d.copy()。当您将字典嵌套到d字典中时,它将返回无效的浅表副本。要解决此问题,我们必须使用 deepcopy

from copy import deepcopy
list.append(deepcopy(d))

它运作完美!!!