JSON_Derulo
JSON_Derulo

Reputation: 992

Unexpected KeyError: in Python 2.7.10

I am new to coding in Python and I have encountered an unexpected error with my code. Any help with this would be much appreciated

import json
from urllib2 import urlopen

response = urlopen("https://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json")
source = response.read()

# print(source)

data = json.loads(source)

# print(json.dumps(data, indent=2))

usd_rates = dict()

for item in data['list']['resources']:
    name = item['resource']['fields']['name']
    price = item['resource']['fields']['price']
    usd_rates[name] = price
    print name, price

enter image description here

Upvotes: 0

Views: 1338

Answers (2)

Use get to fetch value from json/dict and use a None check.

    import json
    from urllib2 import urlopen

    response = urlopen("https://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json")
    source = response.read()

    # print(source)

    data = json.loads(source)

    # print(json.dumps(data, indent=2))

    usd_rates = dict()

    for item in data['list']['resources']:
        name = item.get('resource').get('fields').get('name')
        price = item.get('resource').get('fields').get('price')
        if name is not None:
            usd_rates[name] = price
            print name, price

Upvotes: 0

dilkash
dilkash

Reputation: 592

You are getting error because there is no tag 'name' under 'resource' > 'fields'.

You can add check if you will not get tag 'name' always:

name = item['resource']['fields'].get('name', '')

Upvotes: 6

Related Questions