Python 因 KeyError 失败

Python Failed with KeyError

def getQuotesYahoo():

    tickerStr = "GOOGL+AMZN"
    yahoo_url ="http://finance.yahoo.com/d/quotes.csv?s=%s&f=saohgb3t1" % (tickerStr)
    retQuotes = {}

    data = urllib2.urlopen(yahoo_url).readlines()

    for d in data:
        p = d.strip().split(',')
        stkInfo = {}
        stkInfo['lastTime'] = p[6]
        stkInfo['last'] = p[1]
        stkInfo['open'] = p[2]
        stkInfo['high'] = p[3]
        stkInfo['low'] = p[4]
        stkInfo['bid'] = p[5]
        tic = p[0]
        print stkInfo
        retQuotes[tic] = stkInfo

    print retQuotes['GOOGL']['last']

此代码因 KeyError 而失败,并且未使用字符串键填充字典。我有基本相同的代码用于 googlefiance。

KeyError: 'GOOGL'

retQuotes:

{'"AMZN"': {'last': '594.60', 'bid': 'N/A', 'high': '597.86', 'low': '589.00', 'lastTime': '"4:00pm"', 'open': '594.32'}, '"GOOGL"': {'last': '759.98', 'bid': 'N/A', 'high': '767.13', 'low': '755.77', 'lastTime': '"4:00pm"', 'open': '765.87'}}

字典中的键似乎是“"GOOGL"”,因此键中有双引号。 (整个字符串实际上是 "GOOGL")所以您需要将其引用为:

retQuotes['"GOOGL"']['last']

尽管看起来(N/A 除外)库存中的所有数据都是有效的 python 文字,这意味着您可以使用 ast.literal_eval 来解析数据作为元组:

d = d.replace("N/A","None")
fields = ast.literal_eval("(%s)"%d) #add round brackets to indicate the data is a tuple

您还可以使用 zipdict 构造函数来缩短声明:

import ast
field_names = ('last','open','high','low','bid','lastTime')
for d in data:
    d = d.replace("N/A","None")
    fields = ast.literal_eval("(%s)"%d) #add round brackets to indicate the data is a tuple
    stock = fields[0]
    stkInfo = dict(zip(field_names,fields[1:]))
    retQuotes[stock] = stkInfo