2

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], [100, 0.16], [250, 0.14],
                         [500, 0.12], [1000, 0.1]],
                'key3':'value3'},
{'Customer B':...

How do I get a 'fees' df that looks like this:

             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

Customers become the Index and first part of value tuple becomes the header

Still learning here, so all help is appreciated. Unfortunately this doesn't feel like basic dictionary/list/df operations...

jpp
  • 159,742
  • 34
  • 281
  • 339
ACF
  • 51
  • 1
  • 11

1 Answers1

3

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
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252