2

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 ?

2
  • Can you show the structure of list_city, list_names, list_age? Commented Feb 9, 2018 at 14:35
  • Please post a MCVE. Commented Feb 9, 2018 at 14:46

1 Answer 1

2

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])]}
Sign up to request clarification or add additional context in comments.

3 Comments

Nice solution +1 :).
Thank you very much, today i learnt something new & am really happy for that. :)
@penta glad to help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.