Aashish
Aashish

Reputation: 27

how can we create dataframe from dictionary of list of dictionary

i have json type data

{'expanded': [{'url': 'ab', 'title': 'bc'}, {'url': 'gh', 'title': 'tr, }, {'url': 'as', 'title': 'Sy'}, {'url': 'jk', 'title': 'kl'}]}
{'inline': [{'url': 'hj', 'title': 'fdr'}, {'url': 'gh', 'title': 'lp'}, {'url': 'yr', 'title': 'ew'}]}
{'inline': [{'url': 'ty', 'title': 'JEE .'}, {'url': 'ht', 'title': 'JEE .'}, {'url': 'lt', 'title': 'bus'}]}

i have this type of data and i want to create dataframe like

    type   url title

0 expended ab bc

1 expended gh sy

2 expended as kl

3 inline hj fdr

4 inline gh lp

Upvotes: 2

Views: 107

Answers (1)

jezrael
jezrael

Reputation: 862541

Use nest list and dict comprehension for lsit of dictioanries, then pass to DataFrame:

L = [{'expanded': [{'url': 'ab', 'title': 'bc'}, {'url': 'gh', 'title': 'tr' }, 
                  {'url': 'as', 'title': 'Sy'}, {'url': 'jk', 'title': 'kl'}]},
{'inline': [{'url': 'hj', 'title': 'fdr'}, {'url': 'gh', 'title': 'lp'},
                {'url': 'yr', 'title': 'ew'}]},
{'inline': [{'url': 'ty', 'title': 'JEE .'}, 
                {'url': 'ht', 'title': 'JEE .'}, {'url': 'lt', 'title': 'bus'}]}]

df = pd.DataFrame([{'type': k, **y} for x in L for k, v in x.items() for y in v])
print (df)
   
       type url  title
0  expanded  ab     bc
1  expanded  gh     tr
2  expanded  as     Sy
3  expanded  jk     kl
4    inline  hj    fdr
5    inline  gh     lp
6    inline  yr     ew
7    inline  ty  JEE .
8    inline  ht  JEE .
9    inline  lt    bus

Upvotes: 2

Related Questions