iRocku iRocku - 4 months ago 17
JSON Question

Dictionary to JSON object conversion

I have 2 long lists (extracted from a csv) both of the same index length.
Example:

l1 = ['Apple','Tomato','Cocos'] #name of product

l2 = ['1','2','3'] #some id's


I made my dictionary with this method:

from collections import defaultdict
d = defaultdict(list)
for x in l1:
d['Product'].append(x)
for y in l2:
d['Plu'].append(y)
print d


This will output:

{'Product': ['Apple', 'Tomato', 'Cocos'], 'Plu': ['1', '2', '3']}

(
Product
and
Plu
are my wanted keys)

Now I've tried to import this to a JavaScript Object like this:

import json
print(json.dumps(d, sort_keys=True, indent=4))


This will output:

{
"Plu": [
"1",
"2",
"3"
],
"Product": [
"Apple",
"Tomato",
"Cocos"
]
}


But my desired output is this:

{
Product:'Apple',
Plu:'1'
},
{
Product:'Tomato',
Plu:'2'
},
{
Product:'Cocos',
Plu:'3'
}




I will later use that to insert values in a MongoDB. What will I have to change in my json.dump (or in my dict?) in order to get a desired output? Also is there a way to save the output in a txt file? (since I will have a big code).

Answer

Rather than using a defaultdict (which doesn't buy you anything in this case), you're better off zipping the lists and creating a dict from each pair:

[{'Product': product, 'Plu': plu} for product, plu in zip(l1, l2)]
Comments