I have three lists like below and I want to create a JSON file from them:
devices = ['iphone', 'ipad', 'ipod', 'watch'],
cities = ['NY', 'SFO', 'LA', 'NJ'],
companies = ['Apple', 'Samsung', 'Walmart']
I have done like below.
First manually create a dictionary:
data = {
'devices': ['iphone', 'ipad', 'ipod', 'watch'],
'cities': ['NY', 'SFO', 'LA', 'NJ'],
'companies': ['Apple', 'Samsung', 'Walmart']
}
Then convert it to JSON format like this:
import json
with open('abc.json', 'w') as outfile:
json.dump(data, outfile, indent=4)
Is there a better way of doing this when we have more number of lists.
Ideally if I have N number of lists, I want to create a JSON formatted file a minimal amount of manual work.
pythonfileimport input_listsif the file name isinput_lists.py) and get a list of attribute names usingdir(input_lists). Then it becomes a matter of iterating through that list and eliminating built-in attributes (those that start and end with a__).