Python & JSON |无法使用索引访问字典

我有一个看起来像这样的程序:

import json
import requests
article_name = "BT Centre"
article_api_url = "https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles={}".format(article_name)
called_data = requests.get(article_api_url)
formatted_data = called_data.json()
print(formatted_data)
pages = formatted_data["query"]["pages"]
print(pages)
first_page = pages[0]["extract"]
print(first_page)

对于第一个打印语句,它打印整个 JSON,它返回这个:

{
  'batchcomplete': '','query':{
    'pages':{
      '18107207':{
        'pageid': 18107207,'ns': 0,'title':'BT Centre','extract': "The BT Centre is the global headquarters and registered office of BT Group..."
      }
    }
  }
}

当我尝试使用 first_page 变量访问“提取”数据时,它返回:

Traceback (most recent call last):
  File "wiki_json_printer.py",line 15,in <module>
    first_page = pages[0]["extract"]
KeyError: 0

问题是,我无法将 first_page 设置为 pages["18107207"]["extract"],因为每篇文章的页面 ID 都会发生变化。


编辑:来自 Ann Zen 作品的解决方案:

您可以使用 for 循环来遍历页面的键 字典,并通过 str.isdigit() 检测哪个是 ID 方法:

for key in pages:
    if key.isdigit():
        print(pages[key]["extract"])
q33342074 回答:Python & JSON |无法使用索引访问字典

您可以使用 for 循环遍历 pages 字典的键,并通过 str.isdigit() 方法检测哪个是 ID:

for key in pages:
    if key.isdigit():
        print(pages[key]["extract"])
,

您可以在 dict 上的迭代器上使用 next 来查找第一个键:

...
key = next(iter(pages))
first_page = pages[key]["extract"]
...
,

pages 是字典而不是 list 你不能通过索引选择它,使用它键

print(pages['18107207']['extract'])

当然下面会起作用,因为 key18107207

for key in pages:
    print(pages[key]["extract"])
本文链接:https://www.f2er.com/895082.html

大家都在问