Rishabh Rishabh - 3 years ago 178
JSON Question

Getting KeyError: in my Python script

I am trying to build script which will download images using Python. I am having a problem in the code as the keyerror in Python v 2.7.11 is occurring. My code is

import urllib, urllib2, demjson, os
json = demjson.JSON()
def read_newbooks_file(path):

data = open(path)
isbnlist = []
for isbn in data.readlines():
return isbnlist

isbns = read_newbooks_file("C:\\newbooks.txt")
print isbns
for isbn in isbns:
url="http://openlibrary.org/api/search?q={%22query%22:%22(isbn_10:(" + isbn + ")%20OR%20%20isbn_13:(" + isbn + "))%22}"
if book["result"]!=[]:
results = book["result"]
print results
url = "http://openlibrary.org/api/get?key=" + results[0]
print data
imgurl = 'http://covers.openlibrary.org/b/olid/' + results[0][3:] + '-M.jpg'
imgfile = urllib.urlretrieve(imgurl, "C:\\" + isbn + ".jpg")
fsize = os.path.getsize(imgfile[0])
if fsize < long(1000):
os.remove("C:\\" + isbn + ".jpg")
gparams = urllib.urlencode({'bibkeys': isbn, 'jscmd':'viewapi','callback':'gcallback'})
opener = urllib2.build_opener(urllib2.HTTPHandler())
request = urllib2.Request('http://books.google.com/books?%s' % gparams)
opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: Gecko/2008092417 Firefox/3.0.3')]
g = opener.open(request).read()
print g
if g != "gcallback({});":
g = g[10:-2]
if gbookinfo[isbn].has_key("info_url"):
print "GB info url: " + gbookinfo[isbn]["info_url"]
if gbookinfo[isbn].has_key("thumbnail_url"):
print "GB thumbnail url: " + gbookinfo[isbn]["thumbnail_url"]
opener = urllib2.build_opener(urllib2.HTTPHandler())
request = urllib2.Request(gbookinfo[isbn]["thumbnail_url"])
opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: Gecko/2008092417 Firefox/3.0.3')]
picfile = open("C:\\" + isbn + "-g.jpg", "w+b")

Error I am getting is

Traceback (most recent call last):
File "C:/Python25/first.py", line 16, in <module>
if book["result"]!=[]:
KeyError: 'result'

Answer Source

When book is empty, or if the key you are trying to check for a value isn't there, you'll get a key error. You can use in to check if a key exists within a dict For example, if book is empty, or missing your key, you can use something like:

if 'result' in book:
    book['result'] = ..... # Do something 

This way, you know that the key exists and that your book['result '] is a valid statement that won't raise a key error. Also, it will help you debug if for example your book dictionary is empty or doesn't have your desired key.

Hope that helps

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download