6

How do I convert a python dictionary to a pandas data frame. This is how I currently do it which is not at all elegant.

import pandas as pd
MyDict={'key1':'value1','key2' : 'value2'}
MyDF=pd.DataFrame.from_dict(MyDict,orient='index',dtype=None)
MyDF.index.name = 'Keys'
MyDF.reset_index(inplace=True)

I just want the 'key:value' pair in MyDict as the rows of a pandas dataframe.

dineshdileep
  • 715
  • 2
  • 13
  • 24

2 Answers2

7
pd.DataFrame({'Keys': MyDict.keys(), 'Values': MyDict.values()})

returns

   Keys  Values
0  key2  value2
1  key1  value1
eumiro
  • 207,213
  • 34
  • 299
  • 261
  • 1
    Will this preserve the order?. In the sense, will the "key:value" pair in the dictionary converted to a "single row" in the data frame?. ( If so, this is exactly what I need) – dineshdileep Jan 05 '16 at 05:22
  • 1
    @dineshdileep - Python dictionaries guarantee corresponding order of `.keys()` and `.values()` as long as there is no modification of the dictionary in between. However, there is no order within a dictionary. So your DataFrame will be consistent, just the order of the rows is "random". – eumiro Jan 05 '16 at 08:11
  • Order of rows is not important for me, but rather the contents of the row. Thanks for the answer. – dineshdileep Jan 05 '16 at 08:35
1

If you want to use loc() to access each row in the DataFrame by key then

MyDF = pd.DataFrame([v for v in MyDict.values()], columns = ['value'],
                    index = [k for k in MyDict.keys()])

MyDF then contains

       value
key2  value2
key1  value1

and

MyDF.loc['key2'].value

returns

value2
SpeedCoder5
  • 8,188
  • 6
  • 33
  • 34