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'}]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With