python nested dictionary to pandas DataFrame

Question:

main_dict = {
'NSE:ACC': {'average_price': 0,
             'buy_quantity': 0,
             'depth': {'buy': [{'orders': 0, 'price': 0, 'quantity': 0},
                               {'orders': 0, 'price': 0, 'quantity': 0},
                               {'orders': 0, 'price': 0, 'quantity': 0},
                               {'orders': 0, 'price': 0, 'quantity': 0},
                               {'orders': 0, 'price': 0, 'quantity': 0}],
                       'sell': [{'orders': 0, 'price': 0, 'quantity': 0},
                                {'orders': 0, 'price': 0, 'quantity': 0},
                                {'orders': 0, 'price': 0, 'quantity': 0},
                                {'orders': 0, 'price': 0, 'quantity': 0},
                                {'orders': 0, 'price': 0, 'quantity': 0}]},
             'instrument_token': 5633,
             'last_price': 2488.9,
             'last_quantity': 0,
             'last_trade_time': '2022-09-23 15:59:10',
             'lower_circuit_limit': 2240.05,
             'net_change': 0,
             'ohlc': {'close': 2555.7,
                      'high': 2585.5,
                      'low': 2472.2,
                      'open': 2575},
             'oi': 0,
             'oi_day_high': 0,
             'oi_day_low': 0,
             'sell_quantity': 0,
             'timestamp': '2022-09-23 18:55:17',
             'upper_circuit_limit': 2737.75,
             'volume': 0},
}

convert dict to pandas dataframe

for example:

symbol last_price net_change Open High Low Close
NSE:ACC 2488.9 0 2575 2585.5 2472.2 2555.7

I am trying pd.DataFrame.from_dict(main_dict)
but it does not work.
please give the best suggestion.

Asked By: Kaushik Dalsaniya

||

Answers:

I would first select the necessary data from your dict and then pass that as input to pd.DataFrame()

df_input = [{
    "symbol": symbol,
    "last_price": main_dict.get(symbol).get("last_price"),
    "net_change": main_dict.get(symbol).get("net_change"),
    "open": main_dict.get(symbol).get("ohlc").get("open"),
    "high": main_dict.get(symbol).get("ohlc").get("high"),
    "low": main_dict.get(symbol).get("ohlc").get("low"),
    "close": main_dict.get(symbol).get("ohlc").get("close")
} for symbol in main_dict]

import pandas as pd
df = pd.DataFrame(df_input)
Answered By: bitflip
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.