意外的KeyError:在Python 2.7.10中

时间:2018-07-04 11:39:10

标签: python python-2.7

我是Python编码的新手,我的代码遇到意外错误。任何帮助,将不胜感激

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

2 个答案:

答案 0 :(得分:6)

您收到错误消息,因为“资源”>“字段”下没有标签“名称”。

您可以添加检查,是否始终不会获得标签“名称”:

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

答案 1 :(得分:0)

使用get从json / dict中获取值并使用None检查。

    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