Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert array to dict

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'}]
like image 948
Zouhair Avatar asked Jul 26 '26 00:07

Zouhair


1 Answers

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.

like image 125
TheSoundDefense Avatar answered Jul 27 '26 14:07

TheSoundDefense