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'}}
答案 0 :(得分:0)
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