Select specific column in Python dictionary?

Question:

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

Asked By: HTMLHelpMe

||

Answers:

import pandas as pd
from yahooquery import Ticker

AAPL = Ticker('AAPL')
earnings_trend = AAPL.earnings_trend

# Extract the required value
growth = earnings_trend['AAPL']['trend'][4]['growth']

# Create a DataFrame
df = pd.DataFrame({'growth': [growth]})
print(df)

Output:

     growth
0  0.219080
Answered By: ma9

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
Answered By: Corralien