Python:字典列表在每次迭代中仅存储最后附加的值 [英] Python: List of dictionary stores only last appended value in every iteration
问题描述
我有这个字典清单:
MylistOfdict = [{'Word': 'surveillance',
'Word No': 1},
{'Word': 'equivocal',
'Word No': 2}]
我想创建一个新的字典列表(word_db2
),其中MylistOfdict
中的每个字典都有3个字典.除了MylistOfdict的键和值之外,每个词典中还应具有值分别为Type 1,Type 2,Type 3和'Card Key'的'Card Type'键
I want to create a new list of dictionary (word_db2
) that has 3 dictionaries for each dictionary in MylistOfdict
. In addition to key and values of MylistOfdict, each of those dictionary should have 'Card Type' key with value Type 1, Type 2, Type 3 and 'Card Key' key with incremental value
代码:
word_db2 = []
key = 1
for i in MylistOfdict:
for j in range(1, 4):
i['Card Type'] = 'Type '+str(j)
i['Card Key'] = key
print(i)
word_db2.append(i)
key += 1
输出:
{'Word No': 1, 'Card Key': 1, 'Word': 'surveillance', 'Card Type': 'Type 1'}
{'Word No': 1, 'Card Key': 2, 'Word': 'surveillance', 'Card Type': 'Type 2'}
{'Word No': 1, 'Card Key': 3, 'Word': 'surveillance', 'Card Type': 'Type 3'}
{'Word No': 2, 'Card Key': 4, 'Word': 'equivocal', 'Card Type': 'Type 1'}
{'Word No': 2, 'Card Key': 5, 'Word': 'equivocal', 'Card Type': 'Type 2'}
{'Word No': 2, 'Card Key': 6, 'Word': 'equivocal', 'Card Type': 'Type 3'}
此输出正确,但word_db2
在每次迭代中仅存储最后附加的值
This output is correct, but word_db2
stores only last appended value in every iteration
print(word_db2)
输出:
[{'Card Key': 3, 'Card Type': 'Type 3', 'Word': 'surveillance', 'Word No': 1},
{'Card Key': 3, 'Card Type': 'Type 3', 'Word': 'surveillance', 'Word No': 1},
{'Card Key': 3, 'Card Type': 'Type 3', 'Word': 'surveillance', 'Word No': 1},
{'Card Key': 6, 'Card Type': 'Type 3', 'Word': 'equivocal', 'Word No': 2},
{'Card Key': 6, 'Card Type': 'Type 3', 'Word': 'equivocal', 'Word No': 2},
{'Card Key': 6, 'Card Type': 'Type 3', 'Word': 'equivocal', 'Word No': 2}]
推荐答案
让我们逐步回顾一下循环主体的逻辑:
Let's review the loop body logic step by step:
- 接受其中一项命令
- 修改
- 将其添加到列表的末尾
因此,您错过的关键点是修改并附加在第一步中选择的相同对象.在代码片段的末尾,word_db2
包含六个对象引用,但只有两个唯一.结果,输出显示相似的行.
So the key point you missed is that you modify and append the same object that was selected on the first step. And at the end of the snippet word_db2
contains six object refs, but only two unique. As a result, the output shows similar rows.
您可以先对字典进行浅拷贝,然后再对其进行修改和附加:
You can make a shallow copy of a dict before modifying and appending it:
for j in range(1, 4):
i = dict(i)
i['Card Type'] = 'Type '+str(j)
i['Card Key'] = key
print(i)
word_db2.append(i)
key += 1
请进一步注意,如果字典包含其他可变对象(例如嵌套字典),则应制作一个深层副本:
As further note, if the dict contains other mutable objects like nested dicts, you should make a deep copy:
import copy
old_dict = {'a': [1, 2, 3], 'b': [4, 5, 6]}
new_dict = copy.deepcopy(old_dict)
old_dict['a'][1] = 7
new_dict['a'][1] # 2
这篇关于Python:字典列表在每次迭代中仅存储最后附加的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!