Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make dictionary entry a pandas dataframe by specifying columns?

I have a dictionary like this:

mydict ={'9788845278518': [['/book/show/24235201-numero-zero', 'Italian'], ['/book/show/10522.Il_nome_della_rosa', 'Italian']]}

And I would like to make it a dataframe like this:

ISBN, LINK, LANG
9788845278518, /book/show/24235201-numero-zero, Italian
9788845278518, /book/show/10522.Il_nome_della_rosa, Italian

So I tried by doing:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df = pd.DataFrame.from_dict(mydict)

And I wanted to use df.explode and then doing transpose, but it didn’t really work because my column is not named. Also, there must be a simpler way to do it…

>Solution :

You could try using a defaultdict before creating a Dataframe, since pandas operations are usually more expensive:

import pandas as pd
from collections import defaultdict

mydict ={'9788845278518': [['/book/show/24235201-numero-zero', 'Italian'], ['/book/show/10522.Il_nome_della_rosa', 'Italian']]}

d = defaultdict(list)
for key,value in mydict.items():
  for v in value:
    d.setdefault('ISBN', []).append(key) 
    d.setdefault('LINK', []).append(v[0])
    d.setdefault('LANG', []).append(v[1])    

df = pd.DataFrame(dict(d))
print(df)
            ISBN                                 LINK     LANG
0  9788845278518      /book/show/24235201-numero-zero  Italian
1  9788845278518  /book/show/10522.Il_nome_della_rosa  Italian
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading