簡體   English   中英

如何從字典中的列表中存儲多個值

[英]How to store multiple values from a list within a dictionary

我有一個字典列表,但我想從名為“price”的字典中存儲 3 個值

我的代碼是

response = yf.Ticker("FB").stats()["price"]

輸出:

{'averageDailyVolume10Day': 19621971,
 'averageDailyVolume3Month': 16023089,
 'circulatingSupply': None,
 'currency': 'USD',
 'currencySymbol': '$',
 'exchange': 'NMS',
 'exchangeDataDelayedBy': 0,
 'exchangeName': 'NasdaqGS',
 'fromCurrency': None,
 'lastMarket': None,
 'longName': 'Facebook, Inc.',
 'marketCap': 960766541824,
 'marketState': 'REGULAR',
 'maxAge': 1,
 'openInterest': None,
 'postMarketChange': None,
 'postMarketPrice': None,
 'preMarketChange': 3.51001,
 'preMarketChangePercent': 0.0103239,
 'preMarketPrice': 343.5,
 'preMarketSource': 'FREE_REALTIME',
 'preMarketTime': 1634736599,
 'priceHint': 2,
 'quoteSourceName': 'Nasdaq Real Time Price',
 'quoteType': 'EQUITY',
 'regularMarketChange': 0.7750244,
 'regularMarketChangePercent': 0.0022795508,
 'regularMarketDayHigh': 343.94,
 'regularMarketDayLow': 339.7,
 'regularMarketOpen': 343.445,
 'regularMarketPreviousClose': 339.99,
 'regularMarketPrice': 340.765,
 'regularMarketSource': 'FREE_REALTIME',
 'regularMarketTime': 1634749118,
 'regularMarketVolume': 8538416,
 'shortName': 'Facebook, Inc.',
 'strikePrice': None,
 'symbol': 'FB',
 'toCurrency': None,
 'underlyingSymbol': None,
 'volume24Hr': None,
 'volumeAllCurrencies': None}

我只想得到 shortName、regularMarketPrice 和符號

我知道如果我想提取一個值,我應該運行

response = yf.Ticker("FB").stats()["price"]["shortName"]

但是有沒有辦法存儲所有 3 個值作為響應?

假設您顯示的output字典存儲在response變量中,您可以試試這個 -

keys = ['shortName', 'regularMarketPrice', 'symbol']
filtered_response = {k:response.get(k) for k in keys}
{'shortName': 'Facebook, Inc.', 
 'regularMarketPrice': 340.765, 
 'symbol': 'FB'}

@RJ 在評論中說得對,但這里有一些解釋:

在這種情況下, yf.Ticker("FB").stats()["price"]["shortName"]將返回整個字典。 所以所有的值都被返回並存儲在response

所以你可以這樣做:

response = yf.Ticker("FB").stats()["price"]
shortName = response["shortName"]
regularMarketPrice = response["regularMarketPrice"]
symbol = response["symbol"]

d = {...}

market_price, name, symbol = [d.get(k) for k in d if k == "regularMarketPrice" or k == "shortName" or k == "symbol"]

print(f'MarketPrice: {market_price}')
print(f'shortName  : {name}')
print(f'symbol     : {symbol}')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM