I have a dictionary I'm getting from an API call. 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
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?
requests.get
gives a 'Response'
object rather than a dict
. Only the latter has an items
method for iteration.
You can use the json
library to retrieve a regular Python dictionary:
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.
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? Well for Answer to this question you can refer enter link description here
Hope this doesn't throw AttributeError
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.