I have 2 lists as follows:
>> a = [u'username', u'first name', u'last name']
>> b = [[u'user1', u'Jack', u'Dawson'], [u'user2', u'Roger', u'Federer']]
I am trying to get an output json like the following:
[
{
"username":"user1",
"first name":"Jack",
"last name":"Dawson"
},
{
"username":"user2",
"first name":"Roger",
"last name":"Federer"
}
]
I am trying to use the zip command as follows:
>> x = []
>> for i in range(0, len(b)):
.. x += zip(a,b[i])
..
But this wasn't givin my desired output. How do i implement this?
zip
will just return a list of tuples. You forgot to convert this list of tuples to a dictionary. You can do it using the dict
constructor. Also you can avoid for loop completely: [dict(zip(a, row)) for row in b]
will create your desired list of dictionaries. Then after building the list you can convert to json. For example:
a = [u'username', u'first name', u'last name']
b = [[u'user1', u'Jack', u'Dawson'], [u'user2', u'Roger', u'Federer']]
import json
print(json.dumps([dict(zip(a, row)) for row in b], indent=1))
Output:
[
{
"username": "user1",
"first name": "Jack",
"last name": "Dawson"
},
{
"username": "user2",
"first name": "Roger",
"last name": "Federer"
}
]
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