简体   繁体   中英

Python: How to convert a dictionary of lists to a JSON object?

I am new to the 'json' library thingy and having trouble converting a dictionary of lists to a JSON object, below are the dictionary I got:

import json

data = {

     'title' : ['Seven days', 'Not Today', 'Bad Moms'],
     'date'  : ['July 17', 'Aug 18', 'Jan 19']

}

json_data = json.dumps(data)

print(json_data)

Here was the result I got:

{"title" : ['Seven days', 'Not Today', 'Bad Moms'], "date" : ['July 17', 'Aug 18', 'Jan 19']}

How to get it structured it in this way:

{"title" : "Seven days","date" : "July 17"}, {"title" : "Not Today","date" : "Aug 18"}, {"title" : "Bad Mom","date" : "Jan 19"}

Thank you.

You can convert your data like this:

d = [{'title': t, 'date': d} for t, d in zip(data['title'], data['date'])]
#[{'title': 'Seven days', 'date': 'July 17'}, 
# {'title': 'Not Today', 'date': 'Aug 18'}, 
# {'title': 'Bad Moms', 'date': 'Jan 19'}]

Dumping this to json will result in some string like:

'[{"title": "Seven days", "date": "July 17"}, {"title": "Not Today", "date": "Aug 18"}, {"title": "Bad Moms", "date": "Jan 19"}]'

If you want your json to have a guaranteed order with regard to the keys in each object, you can use:

from collections import OrderedDict
d = [OrderedDict([('title', t), ('date', d)]) for t, d in zip(data['title'], data['date'])]

Restructure data first:

import json
data = {

 'title' : ['Seven days', 'Not Today', 'Bad Moms'],
 'date'  : ['July 17', 'Aug 18', 'Jan 19']

}
new_data = [{"title":i, "date":b} for i, b in zip(data["title"], data["date"])]
final_data = json.dumps(new_data)

Output:

'[{"date": "July 17", "title": "Seven days"}, {"date": "Aug 18", "title": "Not Today"}, {"date": "Jan 19", "title": "Bad Moms"}]'

A more robust solution:

new_data = [dict(zip(data.keys(), i)) for i in zip(*data.values())]

Note that the solution above is best used in Python2, where the .keys() and .values() are ordered.

You can do this if you wanted to do long version, you just have to put the two fields of data in two lists first.

import json

data = {

     'title' : ['Seven days', 'Not Today', 'Bad Moms'],
     'date'  : ['July 17', 'Aug 18', 'Jan 19']

}

titles = data['title']
dates = data['date']

lst = list()

for i in range(len(titles)):
    a = dict()
    a["title"] = titles[i]
    a["date"] = dates[i]
    lst.append(a)

print json.dumps(lst)

Output will look like:

[{"date": "July 17", "title": "Seven days"}, {"date": "Aug 18", "title": "Not Today"}, {"date": "Jan 19", "title": "Bad Moms"}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM