[英]python 3 get specific value from json dictionary
I have a dictionary I'm getting from an API call.我有一本从 API 调用中得到的字典。 I am trying to grab a specific value from the results.
我试图从结果中获取特定值。
names = requests.get("http://some.api")
The result of that call when printed looks like this打印时该调用的结果如下所示
{'mynames': [{'id': 38, 'name': 'Betsy'}, {'id': 93, 'name': 'Pitbull'}, {'id': 84, 'name': 'Liberty'}]}
I've tried the code below just to grab the result with 'Pitbull' as its name我已经尝试了下面的代码只是为了以“Pitbull”作为其名称来获取结果
filtered_names = {k:v for (k,v) in names.items() if "Pitbull" in v}
I get an error of我得到一个错误
AttributeError: 'Response' object has no attribute 'items'
How can I just grab a specific value from the data that is being pulled from the API call?我怎样才能从从 API 调用中提取的数据中获取特定值?
requests.get
gives a 'Response'
object rather than a dict
. requests.get
给出了一个'Response'
对象而不是一个dict
。 Only the latter has an items
method for iteration.只有后者有迭代的
items
方法。
You can use the json
library to retrieve a regular Python dictionary:您可以使用
json
库来检索常规 Python 字典:
import json
import requests
names = requests.get("http://some.api")
d = json.loads(names.text)
Then note you have a dictionary with one key where the value is a list of dictionaries.然后请注意,您有一本带有一个键的字典,其中的值是一个字典列表。 So you need to access
d['mynames']
to retrieve in-scope dictionaries via a list comprehension.因此,您需要访问
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}
Now one question in our mind must come what does this json.py do?现在我们心中的一个问题必须是这个 json.py 是做什么的? Well for Answer to this question you can refer enter link description here
那么对于这个问题的答案,你可以参考这里输入链接描述
Hope this doesn't throw AttributeError
希望这不会抛出
AttributeError
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.