Search code examples
pythonpandasdataframedictionaryyfinance

Select specific column in Python dictionary?


I would like to select a specific field from a python dictionary. The following code produces a result of 152 lines, but I only want to select one line and output it as a dataframe.

import pandas as pd
from yahooquery import Ticker
AAPL = Ticker('AAPL')
AAPL.earnings_trend

Code above returns 152 lines. Below is a portion of it.

{'AAPL': {'trend': [{'maxAge': 1,
    'period': '0q',
     ,
   {'maxAge': 1,
    'period': '-5y',
    'endDate': None,
    'growth': 0.21908002,
    'earningsEstimate': {'avg': {},
     'low': {},
     'high': {},
     'yearAgoEps': {},
     'numberOfAnalysts': {},
     'growth': {}},
     'downLast90days': {}}}],
  'maxAge': 1}}

I want to print line 130 as a dataframe ('growth': 0.21908002 from above):

enter image description here


Solution

  • You can use:

    import pandas as pd
    from yahooquery import Ticker
    
    symbols = ['MSFT', 'AAPL', 'GOOG']
    
    tickers = Ticker(symbols)
    df = pd.DataFrame([{'symbol': ticker, 'growth': data['trend'][-1]['growth']}
                           for ticker, data in tickers.earnings_trend.items()])
    print(df)
    
    # Output
      symbol   growth
    0   MSFT  0.22542
    1   AAPL  0.21908
    2   GOOG  0.23349