Search code examples
pythonpandasdataframe

converting a nested dictionary to Pandas DataFrame


I'm trying to convert a nested dictionary to a df object. the dictionary looks like this:

result = {
    'result': {
        '2011-12-01': {'A': 53, 'B': 28, 'C': 32, 'D': 0}, 
        '2012-01-01': {'A': 51, 'B': 35, 'C': 49, 'D': 0},
        '2012-02-01': {'A': 63, 'B': 32, 'C': 56, 'D': 0}}}

and my goal is to have a table with the dates (second level keys) as an index, and the A,B,C,D as columns.

date A B C D
2011-12-01 53 28 32 0
2012-01-01 51 35 49 0

I tried to use a for loop to grab the inner keys/values and append() it to a DF, but all I've got was a long DF with a date index followed by a plain index.

My failed attempts:

columns = list(result['result'].values())
print(sorted(columns[0].values()))
df = pd.DataFrame(index=result['result'].keys(), columns=columns[0].keys())
for i in range(len(columns)):
    a = sorted(columns[i].items())
    df = df.append(a)
print(df.to_string())

Solution

  • You can simply use:

    df = pd.DataFrame(d['result']).T
    

    Or:

    df = pd.DataFrame.from_dict(d['result'], orient='index')
    

    Output:

                 A   B   C  D
    2011-12-01  53  28  32  0
    2012-01-01  51  35  49  0
    2012-02-01  63  32  56  0