pythonfixer.io

KeyError: 'rates' - Json from fixer.io - Python


I have this code:

def getExchangeRates():
    rates = []
    response = urlopen('my_key')
    data = response.read()
    rdata = json.loads(data.decode(), parse_float=float) 

    rates.append( rdata['rates']['USD'] )
    rates.append( rdata['rates']['GBP'] )
    rates.append( rdata['rates']['HKD'] )
    rates.append( rdata['rates']['AUD'] )
    return rates

This code was working, but now I get the following error:

Traceback (most recent call last):
File "/home/kristian/.virtualenvs/usio_flask/lib/python3.4/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/home/kristian/.virtualenvs/usio_flask/lib/python3.4/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/kristian/.virtualenvs/usio_flask/lib/python3.4/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/kristian/.virtualenvs/usio_flask/lib/python3.4/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/home/kristian/.virtualenvs/usio_flask/lib/python3.4/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/home/kristian/.virtualenvs/usio_flask/lib/python3.4/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "app/app.py", line 30, in index
rates = getExchangeRates()
File "app/app.py", line 22, in getExchangeRates
rates.append( rdata['rates']['USD'] )
KeyError: 'rates'

The weird thing, is that the rates is being initialized here:

rates = []

Any ideas?


Solution

  • The KeyError is because rates is not a key in the rdata. When looking up a key on a dict, it is always a good idea to catch KeyError or use get which allows you to provide a default value in case the key is not found. The code below illustrates both methods:

    rates_from_rdata = rdata.get('rates', {})
    for rate_symbol in ['USD', 'GBP', 'HKD', 'AUD']:
        try:
            rates.append(rates_from_rdata[rate_symbol])
        except KeyError:
            print ('rate for {} not found in rdata'.format(rate_symbol))
            pass