CodeWalker
CodeWalker

Reputation: 2368

Python - Combine two lists into one json object

I have an executor in Python which addresses 2 functions namely get_tech_courses() and get_music_courses() returning individual lists; 1 and 2 respectively.

List 1.

[
{'title': 'THE COMPLETE PYTHON WEB COURSE', 'downloads': '4', 'views': '88'}, 
{'title': 'THE COMPLETE JAVA WEB COURSE', 'downloads': '16', 'views': '156'}
]

List 2.

[
{'title': 'THE COMPLETE GUITAR COURSE', 'downloads': '18', 'views': '125'}, 
{'title': 'THE COMPLETE KEYBOARD COURSE', 'downloads': '63', 'views': '98'}
]

I want to combine both the lists in a json array tied under the parent, courses like this :

{"courses":
[{'title': 'THE COMPLETE PYTHON WEB COURSE', 'downloads': '4', 'views': '88'}, 

{'title': 'THE COMPLETE JAVA WEB COURSE', 'downloads': '16', 'views': '156'},

{'title': 'THE COMPLETE GUITAR COURSE', 'downloads': '18', 'views': '125'}, 

{'title': 'THE COMPLETE KEYBOARD COURSE', 'downloads': '63', 'views': '98'}]
}


This is not printing proper json.

from concurrent.futures import ThreadPoolExecutor

import tech_course
import music_course
import json

courses = []

with ThreadPoolExecutor(max_workers=2) as executor:
    courses.append(executor.submit(tech_course.get_tech_course).result())
    courses.append(executor.submit(music_course.get_music_course).result())

print(json.dumps(courses))

Upvotes: 2

Views: 15899

Answers (1)

ettanany
ettanany

Reputation: 19806

Try the following:

import json

list_1 = [
    {'title': 'THE COMPLETE PYTHON WEB COURSE', 'downloads': '4', 'views': '88'}, 
    {'title': 'THE COMPLETE JAVA WEB COURSE', 'downloads': '16', 'views': '156'}]

list_2 = [
    {'title': 'THE COMPLETE GUITAR COURSE', 'downloads': '18', 'views': '125'}, 
    {'title': 'THE COMPLETE KEYBOARD COURSE', 'downloads': '63', 'views': '98'}]

res_dict = {"courses": list_1 + list_2 }

to_json = json.dumps(res_dict)

Output:

>>> to_json
'{"courses": [{"downloads": "4", "views": "88", "title": "THE COMPLETE PYTHON WEB COURSE"}, {"downloads": "16", "views": "156", "title": "THE COMPLETE JAVA WEB COURSE"}, {"downloads": "18", "views": "125", "title": "THE COMPLETE GUITAR COURSE"}, {"downloads": "63", "views": "98", "title": "THE COMPLETE KEYBOARD COURSE"}]}'

Upvotes: 8

Related Questions