Need help regarding KeyError

Hi I run this code:

with open("keyword.txt") as f:
   keywords =
# csv file
with open("results.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["domain", "similar domain", "price", "year"])

# Filter similar sold domains by sale price and year

    for domain in keywords:
   # Call appraisl API
       appraisal_res = requests.get(appraisal.format(domain), headers=headers).json()
   # Do not abuse the API
       comparable_sales = appraisal_res["comparable_sales"][0]  
       writer.writerow([domain, comparable_sales["domain"], comparable_sales["price"], comparable_sales["year"]])

the code worked but after the operation ended or in the middle of it, I got this error:

    comparable_sales = appraisal_res["comparable_sales"][0]  
KeyError: 'comparable_sales'

What’s wrong?

It means simply that at that point appraisal_res is a dict, but it doesn’t contain that key. You’ll have to print it out to see what it actually. I’d suggest writing to a logfile while processing so that if/when it fails, you can check the logfile to help you to discover what went wrong.

Well, the error message highlights the appraisal_res["comparable_sales"] part of the line, by putting ~ symbols underneath appraisal_res, and ^ marks under the ["comparable_sales"] part. So appraisal_res is what it tried to use when a problem occurred, and ["comparable_sales"] is what it tried to do with that part. In other words, the code tried to look up ["comparable_sales"] inside appraisal_res, and that didn’t work.
Then it told you that there was a KeyError, meaning, an Error caused by a Key. I assume you wrote the code, so I assume you understood that you want appraisal_res to be a dictionary (that part worked!) and that you want to use "comparable_sales" as a key for the appraisal_res dictionary.
Can you think of a reason why looking up a key in a dictionary might fail? Did you try checking what the dictionary contained at the point, to look for a problem?

1 Like