How to create dataframe from dictionary having list of dictionaries?

Viewed 59

I have a dictionary:

adict = {'dic1': [{'a': True, 'b': False, 'c': True, 'd': True, 'z': False}],
         'dic2': [{'e': True, 'f': False, 'g': False}]}

How can I create dataframe in this format?

True False
dic1 a b
c z
d
dic2 e f
g
1 Answers

Try this:

(pd.DataFrame({i:j[0] for i,j in adict.items()})
.stack()
.to_frame().rename_axis(['d',None])
.assign(cc = lambda x: x.groupby([pd.Grouper(level=1),0]).cumcount())
.reset_index(level=0)
.set_index([0,'cc'],append=True)['d']
.unstack(level=1)
.droplevel(1)
.sort_index(axis=1,ascending=False))

Output:

0    True False
dic1    a     b
dic1    c     z
dic1    d   NaN
dic2    e     f
dic2  NaN     g
Related