AnswerBun.com

Forming pandas data frame from both keys and values of dict

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?

Stack Overflow Asked by Rnj on February 22, 2021

2 Answers

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!

Related Questions

Are these Threads synchronized?

3  Asked on November 12, 2020 by haoshoku

     

How to pause and resume a while loop in Python?

5  Asked on November 11, 2020 by mentalcombination

   

How does thrust determine arguments to pass to functor

1  Asked on November 11, 2020 by a_man

     

How can I style specific symbols in an element?

6  Asked on November 10, 2020 by ankit-aggarwal

 

Flutter crash after open apps

4  Asked on November 10, 2020 by zukijuki

       

Java alternative of product function of python form itertools

1  Asked on November 8, 2020 by vipul-tyagi

     

Kubernetes – How to run local image of jenkins

1  Asked on November 8, 2020 by jerome12

   

How to avoid ambiguous template instantiation?

2  Asked on November 8, 2020 by wintergreen_plaza

     

leetcode algorithm edgecase issue

3  Asked on November 7, 2020 by stephen1993

     

Arrows in API strings?

1  Asked on November 6, 2020 by vichofs

   

How to use SQL PARTITION BY GROUPS?

2  Asked on November 5, 2020 by radagast

     

react start cannot find files in public folder

2  Asked on November 5, 2020 by minh-triet

     

tf.keras.utils.to_categorical raises TypeError in graph mode

1  Asked on November 5, 2020 by borun-chowdhury

   

Azure IoT Hub MQTT failure(Without SDK)

1  Asked on November 5, 2020 by govtham

   

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved.