1

I have 3 lists,

city_id = [1,2,3]
city_name = ['a','b','c']
city_capital = ['x','y','z']

How to combine the above three lists into a json in the below format without iterating over by myself. Is there any library function available in python to get the job done?

[
    {
        'city_id': 1,
        'city_name': 'a',
        'city_capital': 'x'
    },
    {
        'city_id': 2,
        'city_name': 'b',
        'city_capital': 'y'
    },
    {
        'city_id': 3,
        'city_name': 'c',
        'city_capital': 'z'
    }
]

1 Answer 1

4

To get a list with data in that form:

[ { 'city_id': x, 'city_name': y, 'city_capital': z } 
  for x, y, z in zip(city_id, city_name, city_capital) ]

If you want to output the data in exactly that form, then you can use the suggestion by @AndyKubiak in the comments:

import json
d = [ { 'city_id': x, 'city_name': y, 'city_capital': z } 
      for x, y, z in zip(city_id, city_name, city_capital) ]
pretty_json = json.dumps(d, sort_keys=True, indent=4)
Sign up to request clarification or add additional context in comments.

1 Comment

I'd just add a call to import json, then wrap that beautiful comprehension of yours with pretty_json = json.dumps(beautiful_comprehension, sort_keys=True, indent=4) from the "Pretty printing" example here.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.