codingknob codingknob - 2 months ago 8x
Python Question

turning dictionary of of dictionary into dataframe with one row, one column of tuples

I have a dictionary named test like so:

dct = {}
test = {'A': 1, '-A': 1, '-C': 1}
dct['key1'] = test

I want a df with one row with one column that looks like:

(A,1), (-A,1), (-C,1)

I've tried so many ways to iteritems() through the keys,value of dct creating list/tuple objects prior to invoking pd.DataFrame(x) but haven't been able to get the structure I want.

There must be an easy way to do this.


You will need to store the elements in some container if you want multiple elements from the dict under a single column:

import  pandas as pd
dct = {}
test = {'A': 1, '-A': 1, '-C': 1}
test2 = {'A': 1, '-A': 1, '-C': 1}
dct['key1'] = test
dct["keys2"] = test2

print(pd.DataFrame([[d.items()] for d in dct.values()]))

Which will give you:

0  [(A, 1), (-A, 1), (-C, 1)]
1  [(A, 1), (-A, 1), (-C, 1)]