[英]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.