【问题标题】:Get all elements from JSON into a list in python将JSON中的所有元素获取到python中的列表中
【发布时间】:2019-08-15 11:40:25
【问题描述】:

我收到了来自 https://en.wikipedia.org/w/api.php?action=query&titles=Web%20Bot&prop=links&pllimit=max&format=json 的以下 JSON 响应

{'batchcomplete': '', 'query': {'pages': {'24482718': {'pageid': 24482718, 'ns': 0, 'title': 'Web Bot', 'links': [{'ns': 0, 'title': '2004 Indian Ocean earthquake'}, {'ns': 0, 'title': '2012 phenomenon'}, {'ns': 0, 'title': 'Algorithm'}, {'ns': 0, 'title': 'Barack Obama'}, {'ns': 0, 'title': 'Daily Telegraph'}, {'ns': 0, 'title': 'Doomsday 2012'}, {'ns': 0, 'title': "Earth's magnetic field"}, {'ns': 0, 'title': 'El Día (La Plata)'}, {'ns': 0, 'title': 'Global Consciousness Project'}, {'ns': 0, 'title': 'Google Flu Trends'}, {'ns': 0, 'title': 'Google Trends'}, {'ns': 0, 'title': 'History (U.S. TV channel)'}, {'ns': 0, 'title': 'Hurricane Katrina'}, {'ns': 0, 'title': 'Internet bot'}, {'ns': 0, 'title': 'Internet bots'}, {'ns': 0, 'title': 'Iran'}, {'ns': 0, 'title': 'Israel'}, {'ns': 0, 'title': 'Northeast Blackout of 2003'}, {'ns': 0, 'title': 'Nostradamus Effect'}, {'ns': 0, 'title': 'Pacific Northwest'}, {'ns': 0, 'title': 'Postdiction'}, {'ns': 0, 'title': 'Predictive analytics'}, {'ns': 0, 'title': 'Pseudoscientific'}, {'ns': 0, 'title': 'Seeking Alpha'}, {'ns': 0, 'title': 'The Epoch Times'}, {'ns': 0, 'title': 'The Globe and Mail'}, {'ns': 0, 'title': 'The Jerusalem Post'}, {'ns': 0, 'title': 'Vancouver, British Columbia'}, {'ns': 4, 'title': 'Wikipedia:Verifiability'}, {'ns': 14, 'title': 'Category:Articles with failed verification from August 2015'}, {'ns': 14, 'title': 'Category:Use dmy dates from January 2012'}]}}}, 'limits': {'links': 500}}

我想将所有标题都放入一个列表中 [2004 Indian Ocean earthquake, 2012 phenomenon, Barack Obama ... ]

我做了以下事情:

json_doc = urllib.request.urlopen(url).read().decode(encoding="utf-8", errors="ignore")
list_of_titles = []
page_id = parsed['query']['pages']
first = next(iter(page_id.values()))
for element in first['links']:
    list_of_elements.append(element['title'])

没有丑陋和嵌套循环的最简单方法是什么?

【问题讨论】:

  • 使用 pydash,它是 JavaScript 的 lodash 的 python 等价物。我鼓励您阅读文档,答案将不言而喻

标签: python json dictionary


【解决方案1】:

您的代码对我来说看起来不错,但您可以使用列表推导将其缩短一点:

...
list_of_elements = []
for page in parsed["query"]["pages"].values():
    list_of_elements.extend([link["title"] for link in page["links"]])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-14
    • 1970-01-01
    相关资源
    最近更新 更多