TransWikia.com

Forming pandas data frame from both keys and values of dict

Stack Overflow Asked by Rnj on February 22, 2021

I have a python dict:

{'key1':'val1', 'key2':'val2', 'key3':'val3', 'key4':'val4'}

I want to convert this to data frame like this:

col1   col2
key1    val1
key2    val2
key3    val3
key4    val4

How do I do this?

2 Answers

You can simply pass dict.items() in Dataframe constructor:

In [265]: data = {'key1':'val1', 'key2':'val2', 'key3':'val3', 'key4':'val4'}

In [269]: df = pd.DataFrame(data.items(), columns=['col1', 'col2'])

In [270]: df
Out[270]: 
   col1  col2
0  key1  val1
1  key2  val2
2  key3  val3
3  key4  val4

OR, use from_dict:

In [362]: df = pd.DataFrame.from_dict(data, orient='index', columns=['col2']).reset_index().rename(columns={'index':'col1'})

In [363]: df
Out[363]: 
   col1  col2
0  key1  val1
1  key2  val2
2  key3  val3
3  key4  val4

Correct answer by Mayank Porwal on February 22, 2021

import pandas as pd
data={'key1':'val1', 'key2':'val2', 'key3':'val3', 'key4':'val4'}
df=pd.DataFrame(list(zip(data,data.values())), columns =['col1', 'col2'])
print(df)

Answered by NoobCoder on February 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP