首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >KeyError,在从api调用获取资源时找不到密钥。

KeyError,在从api调用获取资源时找不到密钥。
EN

Stack Overflow用户
提问于 2022-01-09 07:14:02
回答 1查看 115关注 0票数 0

为什么我会犯一个关键错误?我已经使用第一个id检查了站点,它有一个“后代”键。提前谢谢。

代码语言:javascript
复制
Traceback (most recent call last):
  File "c:\Users\Ronel_Priela\Desktop\Python\Crash_course\ch17_working_w_api\hn_submissions.py", line 24, in <module>
    'comments': id_dictionary['descendants'],
KeyError: 'descendants'

这是我的密码:

代码语言:javascript
复制
from operator import itemgetter
import requests

#API call
url = 'https://hacker-news.firebaseio.com/v0/topstories.json'
r = requests.get(url)
print(r.status_code)

#Storing response
response_dicts = r.json()

#Calling another API for each id
dictionary_profiles = []
for id in response_dicts[:30]:
    url = f"https://hacker-news.firebaseio.com/v0/item/{id}.json"
    r=requests.get(url)
    id_dictionary = r.json()
    print(f'ID: {id} Status: {r.status_code}')

    ##Create dictionary profiles for each id
    dictionary_profile = {
        'title': id_dictionary['title'],
        'hn_link': f"https://news.ycombinator.com/item?id={id}",
        'comments': id_dictionary['descendants'],
    }
    dictionary_profiles.append(dictionary_profile)

print(dictionary_profiles)

这是打印id_dictionary的结果,我得到了我期望的结果。

代码语言:javascript
复制
{'by': 'signa11', 'descendants': 5, 'id': 29860951, 'kids': [29861081, 29861176, 29861155, 29861086, 29861179], 'score': 13, 'time': 1641711518, 'title': 'Literate programming: Knuth is doing it wrong (2014)', 'type': 'story', 'url': 'http://akkartik.name/post/literate-programming'}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-09 07:44:50

以下网站没有'descendants'键(这是列表中的第27个网站):

代码语言:javascript
复制
url = "https://hacker-news.firebaseio.com/v0/item/29856193.json"

内容如下:

{"by":"festinalente","id":29856193,“记分”:1,"time":1641675620,"title":"Finley (YC W21),在英语和销售中招聘金融科技基础设施“,"type":"job","url":"https://www.finleycms.com/careers/"}

您可以使用dict.get方法来避免任何错误。如果指定的键在字典中,则dict.get方法返回指定键的值;如果不返回,默认情况下不返回任何值。因此,如果您按照下面的方式更改构造dictionary_profile的代码,您的代码就会正常工作(没有'title''descendants'键的网站在dictionary_profile中没有这些键)。

代码语言:javascript
复制
dictionary_profile = {
        'title': id_dictionary.get('title'),
        'hn_link': f"https://news.ycombinator.com/item?id={id}",
        'comments': id_dictionary.get('descendants'),
    }
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70639201

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档