Python与JSON技术问题:无法通过索引访问维基百科API返回的动态键字典数据
The Problem
You’re trying to fetch a Wikipedia article’s summary via their API, but hitting a KeyError: 0 when trying to access the extract field. Here’s your original code:
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)
When you run this, the API returns JSON where the pages object is a dictionary (not a list) with a dynamic string key (the page ID, like 18107207):
{ '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..." } } }
The error happens because you’re treating pages like a list and trying to index it with [0], but it’s actually a dict with numeric string keys. Hardcoding the page ID (like pages["18107207"]) also won’t work since it changes per article.
Solutions
1. Iterate to find the numeric page ID (Ann Zen’s approach)
Loop through the keys of the pages dict and check for a numeric key (which is always the page ID in this response):
for key in pages: if key.isdigit(): print(pages[key]["extract"])
2. Directly get the first page value (simpler for single article queries)
Since you’re querying a single article, the pages dict will only have one entry. You can grab its value directly without looping:
# Get the first (and only) page object from the pages dict page = next(iter(pages.values())) print(page["extract"])
This works because iter(pages.values()) creates an iterator over the dict’s values, and next() grabs the first one—perfect when you know there’s only one article result.
内容的提问来源于stack exchange,提问作者GameDesert

