Creating json from lists using zip

I have 2 lists:

>> 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 json output as follows:

[
  {
    "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 that was not my desired outcome. How to implement this?

+4
source share
1 answer

zipjust returns a list of tuples. You forgot to convert this list of tuples to a dictionary. You can do this using the constructor dict. You can also completely eliminate the loop: [dict(zip(a, row)) for row in b]create the desired list of dictionaries. Then after creating the list, you can convert to json. For instance:

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))

Conclusion:

[
 {
  "username": "user1", 
  "first name": "Jack", 
  "last name": "Dawson"
 }, 
 {
  "username": "user2", 
  "first name": "Roger", 
  "last name": "Federer"
 }
]
+6
source

All Articles