Python 如何从以下代码中获取词典列表?

Python 如何从以下代码中获取词典列表?,python,python-3.x,list,dictionary,Python,Python 3.x,List,Dictionary,我需要一份字典清单。字典是从两个不同的列表创建的,其中一个是列表列表。我只得到最后一次迭代的结果作为输出。我可以知道我在下面的代码中犯了什么错误吗?事先非常感谢你 d = ['Good','Bad','Lazy'] main_list=[[0,1,2],[3,4,5],[6,7,8]] dict2={"eventType": "custom Event Name", "attribute1": "value"} list1=[] for item in main_list: dict2

我需要一份字典清单。字典是从两个不同的列表创建的,其中一个是列表列表。我只得到最后一次迭代的结果作为输出。我可以知道我在下面的代码中犯了什么错误吗?事先非常感谢你

d = ['Good','Bad','Lazy']
main_list=[[0,1,2],[3,4,5],[6,7,8]]
dict2={"eventType": "custom Event Name", "attribute1": "value"}
list1=[]

for item in main_list:
    dict2.update(dict(zip(d,item)))
    list1.append(dict2)

print("LIST: ",list1)
预期产出:

 LIST:  [{'eventType': 'custom Event Name', 'attribute1': 'value', 'Good': 0, 'Bad': 1, 'Lazy': 2}, {'eventType': 'custom Event Name', 'attribute1': 'value', 'Good': 3, 'Bad': 4, 'Lazy': 5}, {'eventType': 'custom Event Name', 'attribute1': 'value', 'Good': 6, 'Bad': 7, 'Lazy': 8}]
我得到的输出:

LIST:  [{'eventType': 'custom Event Name', 'attribute1': 'value', 'Good': 6, 'Bad': 7, 'Lazy': 8}, {'eventType': 'custom Event Name', 'attribute1': 'value', 'Good': 6, 'Bad': 7, 'Lazy': 8}, {'eventType': 'custom Event Name', 'attribute1': 'value', 'Good': 6, 'Bad': 7, 'Lazy': 8}]

请尝试以下操作,而不是此行
list1.append(dict2)

from copy import deepcopy

list1.append(deepcopy(dict2))
您的代码运行良好。唯一的问题是,在下一次迭代中,每次都将
dict2
添加到列表中。更改
dict2
时,将更改以前添加到列表中的所有项目


使用
copy
模块,您将在列表中创建
dict2
的副本,并通过更改
dict2
将以前的项目保持原样,以便更好地理解将
打印(列表1)
放入循环中

请尝试以下操作,而不是此行
list1.append(dict2)

from copy import deepcopy

list1.append(deepcopy(dict2))
您的代码运行良好。唯一的问题是,在下一次迭代中,每次都将
dict2
添加到列表中。更改
dict2
时,将更改以前添加到列表中的所有项目


使用
copy
模块,您将在列表中创建
dict2
的副本,并通过更改
dict2
将以前的项目保持原样,以便更好地理解将
打印(列表1)
放入循环中

这是因为您总是更新相同的
dict
实例

解决此问题的一种方法是使用更新的字段创建一个新的本地实例:

主列表中项目的
:
更新的dict=dict(dict2,**dict(zip(d,项目)))
列表1.追加(已更新)

作为旁注,您可以使用列表理解来实现完全相同的事情,这会产生更紧凑(并且可以说更干净)的代码


这是因为您总是更新相同的
dict
实例

解决此问题的一种方法是使用更新的字段创建一个新的本地实例:

主列表中项目的
:
更新的dict=dict(dict2,**dict(zip(d,项目)))
列表1.追加(已更新)

作为旁注,您可以使用列表理解来实现完全相同的事情,这会产生更紧凑(并且可以说更干净)的代码


非常感谢你。当我尝试代码时,我得到的键值对的顺序已经改变。有没有办法以相同的键值对顺序获得输出?@anaghapramesh如果您关心顺序,可以执行
updated_dict=dict(dict2,**dict(zip(d,item))
。我相应地更新了我的答案。非常感谢。当我尝试代码时,我得到的键值对的顺序已经改变。有没有办法以相同的键值对顺序获得输出?@anaghapramesh如果您关心顺序,可以执行
updated_dict=dict(dict2,**dict(zip(d,item))
。我相应地更新了我的答案。