Error in running the code

  1 chapter_to_id = {v: k for k, v in chapter_ids.items()}

----> 2 [x for x in resp.elements if x[“metadata”].get(“parent_id”) == chapter_to_id[“ICE-HOCKEY”]][0]

Cell In[14], line 2, in (.0)
1 chapter_to_id = {v: k for k, v in chapter_ids.items()}
----> 2 [x for x in resp.elements if x[“metadata”].get(“parent_id”) == chapter_to_id[“ICE-HOCKEY”]][0]

KeyError: ‘ICE-HOCKEY’
How to rectify the code, I run the same code as it is in the notebook

Steps to take

  • make sure to have ICE-HOCKEY in the chapters array
  • then do a search as I have shown below in the code
chapters = [
    "THE SUN-SEEKER",
    "RINKS AND SKATERS",
    "TEES AND CRAMPITS",
    "ICE-HOCKEY",
    "SKI-ING",
    "NOTES ON WINTER RESORTS",
    "FOR PARENTS AND GUARDIANS",
]

# assemble chapter_ids json object 
# - with key=element_id, value=Title
chapter_ids = {}
for element in resp.elements:
    # print(f"element: {element}")
    for chapter in chapters:
        if chapter in element["text"] and element["type"] == "Title":
            chapter_ids[element["element_id"]] = chapter
            break

# get chapter ids
chapter_to_id = {v: k for k, v in chapter_ids.items()}
# print(f"chapter_to_id: {chapter_to_id}")

# make sure to check for x["metadata"].get["parent_id"] Not None condition
[x for x in resp.elements if x["metadata"].get("parent_id") is not None 
and chapter_to_id["ICE-HOCKEY"] in x["metadata"].get("parent_id")][0]


This will yield the following output →

{'type': 'NarrativeText',
 'element_id': '24a39efc765a60db62dd23405133a957',
 'text': 'Many of the Swiss winter-resorts can put into the field a very strong ice-hockey team, and fine teams from other countries often make winter tours there; but the ice-hockey which the ordinary winter visitor will be apt to join in will probably be of the most elementary and unscientific kind indulged in, when the skating day is drawing to a close, by picked-up sides. As will be readily understood, the ice over which a hockey match has been played is perfectly useless for skaters any more that day until it has been swept, scraped, and sprinkled or flooded; and in consequence, at all Swiss resorts, with the exception of St. Moritz, where there is a rink that has been made for the hockey-player, or when an important match is being played, this sport is supplementary to such others as I have spoken of. Nobody, that is, plays hockey and nothing else, since he cannot play hockey at all till the greedy skaters have finished with the ice.',
 'metadata': {'languages': ['eng'],
  'parent_id': '67d58ab3aae6e41e9ce429dc4cbe5501',
  'filename': 'winter-sports.epub',
  'filetype': 'application/epub'}}

Thank you for the solution and I got the same output.

Regards
Krishnaveni A