Home > Software engineering >  Converting a list of lists to Json with hard coded format using python
Converting a list of lists to Json with hard coded format using python

Time:11-13

Consider i have a list of lists like below

mylist = [(1, "Laprovitola", "Italy")]

Imagine i have 1000 sublists. I'd like to make a format of

 mydict = [{
             "ID": "1",
             "Name": "Laprovitola",
             "CountryOfResidence": "Italy"} 
   ]

etc... The dict should have 8 values in total ID name country and more. any solution on this?

I have tried the previous solution but have not worked on my hard-coded Dict.

CodePudding user response:

One way of doing it is having a tuple of column names and zip it with each sub list:

import json

mylist = [(1, "Laprovitola", "Italy")]
coloumns = ("ID", "name", "country")

list_of_dicts = [dict(zip(coloumns, item)) for item in mylist]

print(json.dumps(list_of_dicts))

CodePudding user response:

You can unpack the tuple when iterating the list, create dict and append it to the new list.

mylist = [(1, "Laprovitola", "Italy")]

mydict = []
for ID, Name, CountryOfResidence in mylist:
    dct = {}
    dct['ID'], dct['Name'], dct['CountryOfResidence'] = ID, Name, CountryOfResidence
    mydict.append(dct)

print(mydict)

# [{'ID': 1, 'Name': 'Laprovitola', 'CountryOfResidence': 'Italy'}]
  • Related