【问题标题】:Python - Combine two lists into one json objectPython - 将两个列表组合成一个 json 对象
【发布时间】:2017-04-12 06:55:25
【问题描述】:

我在 Python 中有一个执行器,它处理两个函数,即 get_tech_courses() 和 get_music_courses() 返回单个列表;分别为 1 和 2。

清单 1。

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

清单 2。

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

我想将两个列表合并到一个 json 数组中,该数组绑定在父级 courses 下,如下所示:

{"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'}]
}


这没有打印正确的 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))

【问题讨论】:

  • 怎么样:combined_lists = {"courses": list1+list2}。这不是你想要的吗?

标签: python json list python-3.x


【解决方案1】:

尝试以下方法:

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)

输出:

>>> 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"}]}'

【讨论】:

  • 在我的问题中,我将执行者的结果附加到 courses 列表中。我们可以这样做吗?
  • 如果课程是一个列表并且您想向其中添加另一个列表的元素,您将需要使用extend 而不是append
  • 成功了!干杯。
猜你喜欢
  • 1970-01-01
  • 2016-11-12
  • 1970-01-01
  • 1970-01-01
  • 2019-12-19
  • 2022-01-04
  • 2018-10-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多