Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 传递给有序Dict creation的列表理解被创建为引用_Python_Python 3.x_List_Dictionary_Ordereddictionary - Fatal编程技术网

Python 传递给有序Dict creation的列表理解被创建为引用

Python 传递给有序Dict creation的列表理解被创建为引用,python,python-3.x,list,dictionary,ordereddictionary,Python,Python 3.x,List,Dictionary,Ordereddictionary,我正在尝试为给定的一组密钥创建一个有序的dic。 我想要的是什么` OrderedDict([('A', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), ('B', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), ('C', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), ('D', [0, 0, 0, 0, 0, 0,

我正在尝试为给定的一组密钥创建一个有序的dic。 我想要的是什么`

     OrderedDict([('A', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), 
                  ('B', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), 
                  ('C', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), 
                  ('D', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0])])`
这是由以下函数创建的

d=OrderedDict.fromkeys(键,[0表示范围(10)])

我正在成功地获得所需的结构

问题是dict all的值被创建为引用。这意味着当我尝试执行以下操作时,
d['A'][1]=“11111”
它更改了给定的每个键的值。 我得到的结果如下

    OrderedDict([('A', [0, '11111', 0, 0, 0, 0, 0, 0, 0, 0]), 
                 ('B', [0, '11111', 0, 0, 0, 0, 0, 0, 0, 0]), 
                 ('C', [0, '11111', 0, 0, 0, 0, 0, 0, 0, 0]), 
                 ('D', [0, '11111', 0, 0, 0, 0, 0, 0, 0, 0])])
我确实试过deepcopy,但没有真正的帮助。 我目前的工作是

d['A'] = d['A'][:]
我真的不喜欢上面的解决方案,因为我有大约6mil的键和值。。所以这样做有点麻烦

我想知道一个更好的方法。。以及发生这种情况的原因。

classmethod对所有字典键使用相同的默认值

要避免这种情况,请为每个键指定一个新实例:

d = OrderedDict((k, [0]*10) for k in keys)

我相信,如果您可以迭代每个列表并对其调用
list()
,您将得到一个不包含链接引用的列表。@JammyDodger我确实尝试过,但似乎不起作用。。