0

I have a dictionary of the following form:

{'x': 1, 'y': 2, 'z':{'a': 3, 'b': 4}, 'w': {'a': 5, 'b': 6}}

I want to create a df like this:

enter image description here

What is the best way to achieve this?

rivu
  • 2,004
  • 2
  • 29
  • 45

1 Answers1

2

If you have only 2 levels:

import pandas as pd

d = {'x': 1, 'y': 2, 'z':{'a': 3, 'b': 4}, 'w': {'a': 5, 'b': 6}}

data = {}
for k1, v1 in d.items():
    if isinstance(v1, dict):
        for k2, v2 in v1.items():
            data[(k1, k2)] = v2
    else:
        data[(k1, '')] = v1

df = pd.DataFrame([data.values()], columns=data)

Output:

>>> df
   x  y  z     w      # index, level 1
         a  b  a  b   # index, level 2
0  1  2  3  4  5  6   # values
Corralien
  • 109,409
  • 8
  • 28
  • 52
  • Thanks for the quick reply! For now, I have 2 levels, but in the future, I might have a third level. If you have a more general solution, that would be awesome! – rivu Nov 16 '21 at 21:12