Search code examples
pythonjsonlist-comprehensiondictionary-comprehension

How to create the Json schema in python?


I want to create the below json schema in python.

{
    "persons": [
        {
            "city": "Seattle", 
            "name": "Brian",
            "age" : 19
        }, 
        {
            "city": "Amsterdam", 
            "name": "David",
            "age" : 29
        }, 
        {
            "city": "Amsterdam", 
            "name": "David",
            "age" : 19
        }, 
        {
            "city": "Amsterdam", 
            "name": "David",
            "age" : 49
        }, 
        {
            "city": "Amsterdam", 
            "name": "David",
            "age" : 19
        }
    ]
}

I have 3 lists.

    city=list_city[10::9]
    name=list_names[9::9][::-1]
    age=list_age[11::9]

I have spent few hours to accomplish this by list,dict comprehensions, but I at max get just one Json object inside the persons array.

Like this :-

{
    "persons": [
        {
            "city": "Seattle", 
            "name": "Brian",
            "age" : 19
        } "age" : 19

    ]
}

Which I suspect is because the dictionary is getting updated & thereby overwriting old values.

How can I achieve the complete json schema ?


Solution

  • You can create the dictionary by using a list comprehension with zip:

    city=list_city[10::9]
    name=list_names[9::9][::-1]
    age=list_age[11::9]
    final_data = {'persons':[dict(zip(['city', 'name', 'age'], i)) for i in zip(*[city, name, age])]}