import requests
import json
def jprint(obj):
text = json.dumps(obj, sort_keys=True, indent=4)
if name == "main":
response = requests.get("https://anapioficeandfire.com/api/characters/583")
jprint(response.json())
data_list = response.json()
my_dictionary = data_list[0]
tvSeries = int(input("What series do you want to search?"))
final_dictionary = {}
for elem in data_list:
name = ''
for key, value in elem.items():
if( key == "name"):
name=value
if( key == 'tvSeries'):
if tvSeries in value:
print(name)
The code above is what I have tried so far. My goal is to get the program to list off each person from the API who appears in the user-identififed tvSeries. I keep getting an error in line 18 because of the 0. I also get an error in line 25 saying that items has not been defined. If anyone can help, that would be great.
Here is the API:
{
"url": "https://anapioficeandfire.com/api/characters/583",
"name": "Jon Snow",
"gender": "Male",
"culture": "Northmen",
"born": "In 283 AC",
"died": "",
"titles": [
"Lord Commander of the Night’s Watch"
],
"aliases": [
"Lord Snow",
"Ned Stark’s Bastard",
"The Snow of Winterfell",
"The Crow-Come-Over",
"The 998th Lord Commander of the Night’s Watch",
"The Bastard of Winterfell",
"The Black Bastard of the Wall",
"Lord Crow"
],
"father": "",
"mother": "",
"spouse": "",
"allegiances": [
"https://anapioficeandfire.com/api/houses/362"
],
"books": [
"https://anapioficeandfire.com/api/books/5"
],
"povBooks": [
"https://anapioficeandfire.com/api/books/1",
"https://anapioficeandfire.com/api/books/2",
"https://anapioficeandfire.com/api/books/3",
"https://anapioficeandfire.com/api/books/8"
],
"tvSeries": [
"Season 1",
"Season 2",
"Season 3",
"Season 4",
"Season 5",
"Season 6"
],
"playedBy": [
"Kit Harington"
]
2
Answers
data_list which is equal to response.json() is dictionary not list and that’s why you are getting KeyError
i have examined the output of your api and realized that the output is a dictionary, but you seem to be treating it as if it were a list
i believe you mean something like this: