我有一个字典,我从API调用。我试图从结果中获取特定值。
names = requests.get("http://some.api")
打印时调用的结果如下所示
{'mynames': [{'id': 38, 'name': 'Betsy'}, {'id': 93, 'name': 'Pitbull'}, {'id': 84, 'name': 'Liberty'}]}
我尝试过以下代码,只是以'Pitbull'作为名称来获取结果
filtered_names = {k:v for (k,v) in names.items() if "Pitbull" in v}
我得到一个错误
AttributeError: 'Response' object has no attribute 'items'
如何从API调用中提取的数据中获取特定值?
requests.get
给出了'Response'
对象而不是dict
。只有后者有一个items
迭代方法。
您可以使用json
库来检索常规Python字典:
import json
import requests
names = requests.get("http://some.api")
d = json.loads(names.text)
然后请注意,您有一个包含一个键的字典,其中值是一个字典列表。因此,您需要访问d['mynames']
以通过列表理解检索范围内的词典。
filtered_names = [el for el in d['mynames'] if 'Pitbull' in el['name']]
# [{'id': 93, 'name': 'Pitbull'}]
import json
names = requests.get('https://api')
Json = json.loads(names)
filtered_names = {k:v for k,v in Json.items() if "Pitbull" in v}
现在我们脑海中的一个问题必定是这个json.py做了什么?那么回答这个问题你可以参考enter link description here
希望这不会抛出AttributeError