意外的KeyError:在Python 2.7.10中

S. *_*ler 0 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
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

dil*_*ash 6

您收到错误,因为'resource'>'fields'下没有标记'name'.

您可以添加检查是否始终不会获得标记'name':

name = item['resource']['fields'].get('name', '')
Run Code Online (Sandbox Code Playgroud)