4

I have a dict like:

`{'10/12/2020': 'Hello', '11/12/2020': 'Bye'}

I want to convert this to a pandas dataframe such that a column is the key and another column is values. How can I do this?

pd.DataFrame.from_dict(data) does not work

jojdmish
  • 41
  • 1
  • 3

3 Answers3

6

Is this what you want?:

import pandas as pd

data = {'10/12/2020': 'Hello', '11/12/2020': 'Bye'}

df = pd.DataFrame(data.items())
print(df)

output:

            0      1
0  10/12/2020  Hello
1  11/12/2020    Bye
  • Caustion: Before 3.7(3.6 for CPython) version python interpreter, dictionaries don't ensure ordering. You should use collections.OrderedDict for ordered dict for those versions.
Boseong Choi
  • 2,566
  • 9
  • 22
0

It's not a problem if you use the list format.

import pandas as pd

data = [{'10/12/2020': 'Hello', '11/12/2020': 'Bye'}]

df = pd.DataFrame.from_dict(data)

df
10/12/2020  11/12/2020
0   Hello   Bye
r-beginners
  • 31,170
  • 3
  • 14
  • 32
0

A key-value dictionary is more akin to a Series, try doing a Series and then converting that to a DataFrame.

>>> import pandas as pd
>>> data = {'10/12/2020': 'Hello', '11/12/2020': 'Bye'}
>>> pd.Series(data).to_frame("whatever you want the column name to be")
           whatever you want the column name to be
10/12/2020                                   Hello
11/12/2020                                     Bye
>>> pd.Series(data).to_frame("whatever you want the index name to be").T
                                       10/12/2020 11/12/2020
whatever you want the index name to be      Hello        Bye
O.rka
  • 29,847
  • 68
  • 194
  • 309