Pandas dataframe from nested dictionary

My dictionary is as follows:

{'x': {'b': 10, 'c': 20}, 'y': {'b': '33', 'c': 44}}

I want to get a dataframe that looks like this:

index   col1    col2    val
0        x       b      10
1        x       c      20
2        y       b      33
3        y       c      44

I tried calling pandas.from_dict (), but it did not give me the desired result. So what is the most elegant, practical way to achieve this?

EDIT: In fact, my dictionary has a depth of 4, so I would like to see a solution for this case or, ideally, one that will work at an arbitrary depth in the overall setup.

Here is an example of a deeper dictionary: The {'x':{'a':{'m':1, 'n':2}, 'b':{'m':10, 'n':20}}, 'y':{'a':{'m':100, 'n':200}, 'b':{'m':111, 'n':222}} }corresponding data block should contain 8 lines.

ANSWER:

df = pd.DataFrame([(k1, k2, k3, k4, k5, v) for k1, k2345v in dict.items()
                           for k2, k345v in k2345v.items()
                           for k3, k45v in k345v.items()
                           for k4, k5v in k45v.items()
                           for k5, v in k5v.items()])
+2
source share
2 answers

, dict , ,

import pandas as pd

d = {'x': {'b': 10, 'c': 20}, 'y': {'b': '33', 'c': 44}}

df = pd.DataFrame([(k,k1,v1) for k,v in d.items() for k1,v1 in v.items()], columns = ['Col1','Col2','Val'])
print df.sort(['Col1','Col2','Val'], ascending=[1,1,1])

  Col1 Col2 Val
3    x    b  10
2    x    c  20
1    y    b  33
0    y    c  44
+2

df from_dict, stack reset_index, , cols, sort reset :

In [83]:
d={'x': {'b': 10, 'c': 20}, 'y': {'b': '33', 'c': 44}}
df = pd.DataFrame.from_dict(d, orient='index').stack().reset_index()
df.columns = ['col1', 'col2', 'val']
df.sort_values(['col1', 'col2'], inplace=True)
df.reset_index(drop=True, inplace=True)
df

Out[83]:
  col1 col2 val
0    x    b  10
1    x    c  20
2    y    b  33
3    y    c  44
+1

All Articles