问题描述
通过for循环创建词典列表
Creating a list of dictionaries via a for loop
我一直在尝试通过for循环创建词典列表,如下所示代码
I've been trying to create a list of dictionaries via a for loop, code shown below
a=["x","y","z"]
b=[1,2,3]
dict1={}
superlist=[]
for i in range(0,len(a)):
dict1['name']=a[i]
dict1['values']=b[i]
superlist.append(dict1)
什么我期望输出为
[{'name':'x','values':1},{'name':'y','values':2} ,{'name':'z','values':3}]
,
相反,我得到
[{'name':'z','values':3},{'name':'z','values':3},{'name ':'z','values':3}]
。
我不太确定这里发生了什么,如果有人可以解释并帮助我获得理想的结果,那就太好了。
I'm not really sure what's going on here and it'd be great if someone can explain and help me get my desired result.
推荐答案
您将在每次迭代后附加对 dict1
的引用,但同时还要更改每次使用这些键,以便在结束时具有对相同dict的引用列表(这就是它们看上去都相同的原因)。
You are appending a reference to dict1
on each iteration, but you are also changing the values of the keys each time so that when you end you have a list of references to the same dict (which is why they all look the same).
简单的解决方法是移动在您的for循环内 dict1 = {}
。这样,您将创建一个具有自己的键值对的新字典,将其添加到每次迭代中。
Simple fix is to move dict1 = {}
inside your for loop. That way you are creating a new dict with its own key value pairs to be appended on each iteration.
这篇关于仅字典的最新值被添加到列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!