Python 如何从字典中取出一只股票最近的当前股价并将其放入一个变量中?

Python How to retrieve a stock's last current stock price from the dictionary and put it into a variable?

我试图获取一只股票的当前价格,然后将它放入一个变量中以运行 if / else 语句上。我已经使用 Google API 检索当前股票价格,但我无法弄清楚如何将其放入变量中。谢谢!

import json
import sys

try:
    from urllib.request import Request, urlopen
except ImportError:  #python 2
    from urllib2 import Request, urlopen

googleFinanceKeyToFullName = {
    u'id'     : u'ID',
    u't'      : u'StockSymbol',
    u'e'      : u'Index',
    u'l'      : u'LastTradePrice',
    u'l_cur'  : u'LastTradeWithCurrency',
    u'ltt'    : u'LastTradeTime',
    u'lt_dts' : u'LastTradeDateTime',
    u'lt'     : u'LastTradeDateTimeLong',
    u'div'    : u'Dividend',
    u'yld'    : u'Yield'
}

def buildUrl(symbols):
    symbol_list = ','.join([symbol for symbol in symbols])
    #a deprecated but still active & correct api
    return 'http://finance.google.com/finance/info?client=ig&q=' \
        + symbol_list

def request(symbols):
    url = buildUrl(symbols)
    req = Request(url)
    resp = urlopen(req)
    #remove special symbols such as the pound symbol
    content = resp.read().decode('ascii', 'ignore').strip()
    content = content[3:]
    return content

def replaceKeys(quotes):
    global googleFinanceKeyToFullName
    quotesWithReadableKey = []
    for q in quotes:
        qReadableKey = {}
        for k in googleFinanceKeyToFullName:
            if k in q:
                qReadableKey[googleFinanceKeyToFullName[k]] = q[k]
        quotesWithReadableKey.append(qReadableKey)
    return quotesWithReadableKey

def getQuotes(symbols):

    if type(symbols) == type('str'):
        symbols = [symbols]
    content = json.loads(request(symbols))
    return replaceKeys(content);

if __name__ == '__main__':
    try:
        symbols = sys.argv[1]
    except:
        symbols = "GOOG,AAPL,MSFT,AMZN,SBUX"

    symbols = symbols.split(',')

    try:
        print(json.dumps(getQuotes(symbols), indent=2))
    except:
        print("Fail")

你可以从字典中得到最近的当前股票价格并将其放入一个变量中,比如price,

通过将代码的最后一部分更改为

 try:
      quotes = getQuotes(symbols)
      price = quotes[-1]['LastTradePrice']  # -1 means last in a  list
      print(price)
  except Exception as e:
      print(e)

但这很不可靠,因为如果价格顺序改变,你会得到不同股票的价格。

你应该做的是学习如何定义适合你的问题的数据结构。