How to create dataframe from dictionary having list of dictionaries?

Question:

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
Asked By: user12252991

||

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))

or

d2 = {True:[],False:[]}

for k,v in d.items():
    for k2,v2 in v[0].items():
        d2.get(v2).append((k,k2))

(v := pd.DataFrame(d2).stack()).to_frame('s').set_index(v.str[0],append=True)['s'].str[-1].unstack(level=1).reset_index(level=0,drop=True)

Output:

0    True False
dic1    a     b
dic1    c     z
dic1    d   NaN
dic2    e     f
dic2  NaN     g
Answered By: rhug123
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.