简体   繁体   中英

How to store multiple values from a list within a dictionary

I have a list of dictionaries but I want to store 3 values from a dictionary named 'price'

My code is

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

output:

{'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}

I would like to get only shortName, regularMarketPrice and symbol

I know that if I want to exctrat one value I should run

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

but is there a way to store all 3 values in response?

Assuming the output dictionary you show is stored in response variable, you can try this -

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

@RJ has it right in the comments, but here some explanation for you:

In this case, yf.Ticker("FB").stats()["price"]["shortName"] is returning you the entire dictionary. So all of values are being returned and stored in response .

So you can just do:

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}')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM