【问题标题】:Python Failed with KeyErrorPython 因 KeyError 失败
【发布时间】:2016-04-11 06:46:18
【问题描述】:
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'}}

【问题讨论】:

  • google 的股票代码不是GOOGL,而是GOOG
  • retQuotes 的结果是什么?打印变量可能会有所帮助。
  • 看起来ticker在结构中。
  • 股票代码是 GOOGL 和 GOOG
  • 啊.. ic 只需要清理引号。谢谢大家

标签: python dictionary populate


【解决方案1】:

似乎字典中的键是'"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

【讨论】:

  • 我认为这也会更快。感谢您的帮助
  • @user3763220 请知道accepting an answer 有一个机制。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-17
  • 1970-01-01
  • 2019-12-20
  • 2018-04-07
相关资源
最近更新 更多