将数组转换为字典

Zou*_*air 6 python arrays dictionary

我想将列表转换为字典:

products=[['1','product 1'],['2','product 2']]
arr=[]
vals={}
for product in products:
    vals['id']=product[0]
    vals['name']=product
    arr.append(vals)
print str(arr)
Run Code Online (Sandbox Code Playgroud)

结果是

[{'id': '2', 'name': 'product 2'}, {'id': '2', 'name': 'product 2'}]
Run Code Online (Sandbox Code Playgroud)

但我想要这样的东西:

[{'id': '1', 'name': 'product 1'}, {'id': '2', 'name': 'product 2'}]
Run Code Online (Sandbox Code Playgroud)

The*_*nse 5

您需要做的是为循环的每次迭代创建一个新字典。

products=[['1','product 1'],['2','product 2']]
arr=[]
for product in products:
    vals = {}
    vals['id']=product[0]
    vals['name']=product[1]
    arr.append(vals)
print str(arr)
Run Code Online (Sandbox Code Playgroud)

当您将append字典等对象添加到数组时,Python在追加之前不会进行复制。它将将该确切的对象附加到数组中。所以如果你添加dict1到一个数组,然后更改dict1,那么数组的内容也会改变。因此,您应该每次都制作一本新词典,如上所述。