Python因KeyError失败

时间:2016-04-10 20:42:58

标签: python dictionary populate

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:00”,“打开”:'594.32'},'“GOOGL”':{'last':'759.98','bid':'N / A','high':'767.13',' low':'755.77','lastTime':'“4:00 pm”','open':'765.87'}}

1 个答案:

答案 0 :(得分:0)

似乎关键词中存在的关键是'" 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

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

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