Search code examples
pandasdataframedictionarykeyrow

Keys as Rows (Pandas Dataframe from dictionary)


I have this dictionary:

d = {'a': (1,2,3), 'b': (4,5,6)}

I would like it to be formed as a dataframe where the key is shown as row along with its corresponding values, like the table below:

Keys Values
a 1
a 2
a 3
b 4
b 5

Any ideas?


Solution

  • Here is my suggestion.

    1. Create your dataframe with the following command:

    df = pd.DataFrame({'Keys': list(dict.keys()), 'Values': list(dict.values())})

    1. Explode your dataframe on column of 'Values' with the following command:

    df = df.explode(column='Values').reset_index(drop=True

    The output result is something like this:

           Keys   Values
      0    a      1
      1    a      2
      2    a      3
      3    b      4
      4    b      5
      5    b      6