Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating json from lists using zip

Tags:

python

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?

like image 563
Abhishek Avatar asked Apr 19 '15 21:04

Abhishek


1 Answers

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"
 }
]
like image 69
JuniorCompressor Avatar answered Sep 29 '22 10:09

JuniorCompressor