Skip to content Skip to sidebar Skip to footer

Split Dict Value Tuples Into Df Headers And Contents In Python3

I have a dictionary that looks like this: {'Customer A': {'key1':'value 1', 'fees': [[0, 0.26], [5, 0.24], [10, 0.22], [25, 0.2], [50, 0.18

Solution 1:

Use dict comprehension with DataFrame.from_dict, last sort columns by sort_index:

d = {'Customer A': {'key1':'value 1',
                'fees': [[0, 0.26], [5, 0.24], [10, 0.22], [25, 0.2],
                         [50, 0.18], [100, 0.16], [250, 0.14],
                         [500, 0.12], [1000, 0.1]],
                'key3':'value3'}, 'Customer B': {'key1':'value 1',
                'fees': [[0, 0.26], [5, 0.24], [10, 0.22], [25, 0.2],
                         [50, 0.18], [100, 0.16], [250, 0.14],
                         [500, 0.12], [1000, 0.1]],
                'key3':'value3'}}


df = pd.DataFrame.from_dict({k: dict(v['fees']) for k, v in d.items()}, orient='index')
print (df)
            0     50    100   5     1000  25    10    500   250 
Customer A  0.26  0.18  0.16  0.24   0.1   0.2  0.22  0.12  0.14
Customer B  0.26  0.18  0.16  0.24   0.1   0.2  0.22  0.12  0.14

df = df.sort_index(axis=1)
print (df)
            0     5     10    25    50    100   250   500   1000
Customer A  0.26  0.24  0.22   0.2  0.18  0.16  0.14  0.12   0.1
Customer B  0.26  0.24  0.22   0.2  0.18  0.16  0.14  0.12   0.1

Post a Comment for "Split Dict Value Tuples Into Df Headers And Contents In Python3"