Reputation: 651
I want to convert a list to a 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)
The result is
[{'id': '2', 'name': 'product 2'}, {'id': '2', 'name': 'product 2'}]
But I want something thing like that:
[{'id': '1', 'name': 'product 1'}, {'id': '2', 'name': 'product 2'}]
Upvotes: 7
Views: 32101
Reputation: 2174
products=[['1','product 1'],['2','product 2']]
arr=[{'id':a[0], 'name': a[1]} for a in products]
print str(arr)
Would also work
Upvotes: 2
Reputation:
For simplicity sake you could also make this into a one liner:
products=[['1','product 1'],['2','product 2']]
arr= [{"id":item[0], "name":item[1]} for item in products]
Which yields:
[{'id': '1', 'name': 'product 1'}, {'id': '2', 'name': 'product 2'}]
Upvotes: 3
Reputation: 1063
products=[['1','product 1'],['2','product 2']]
arr=[]
for product in products:
vals = {}
for i, n in enumerate(['id', 'name', ....]): # to make it more dynamic?
vals[n]=product[i]
arr.append(vals)
or just use [0], [1] like stated in previous post
Upvotes: 0
Reputation: 6935
What you need to do is create a new dictionary for each iteration of the loop.
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)
When you append
an object like a dictionary to an array, Python does not make a copy before it appends. It will append that exact object to the array. So if you add dict1
to an array, then change dict1
, then the array's contents will also change. For that reason, you should be making a new dictionary each time, as above.
Upvotes: 6