Python失败,出现了keyrerror

Python失败,出现了keyrerror,python,dictionary,populate,Python,Dictionary,Populate,此代码在KeyError和未使用字符串键填充字典时失败。我有基本相同的代码为谷歌未婚夫工作 KeyError:“GOOGL” 引述: {'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':

此代码在KeyError和未使用字符串键填充字典时失败。我有基本相同的代码为谷歌未婚夫工作

KeyError:“GOOGL”

引述:

{'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”),因此您需要将其称为:

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']
尽管看起来(除了
N/A
)股票中的所有数据都是有效的python文本,这意味着您可以使用
ast.literal\u eval
将数据解析为元组:

retQuotes['"GOOGL"']['last']
您还可以使用
zip
dict
构造函数来缩短声明:

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

谷歌的股票代码不是
GOOGL
,它是
GOOG
什么会在
retQuotes
中结束?打印变量可能会有帮助。看起来ticker在结构中。ticker是GOOGL和googah。。我只需要整理一下报价。谢谢你,盖伊。我想这也会快得多。谢谢你的邀请help@user3763220请知道,有一个机制。
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