3

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))
1
  • 2
    What about: combined_lists = {"courses": list1+list2}. Is not that what you want? Commented Nov 28, 2016 at 14:07

1 Answer 1

9

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

3 Comments

In my question, I am appending the result of the executors to a courses list. Can we do it in this way ?
If courses is a list and you want to add to it elements of another list, you will need to use extend instead of append
Worked! Cheers.

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.