Python transpose dictionary

74 Views Asked by At

I have

data_dict = {1: {'One': 110, 'Two': 210, 'three': 310},
             2: {'One': 120, 'Two': 220, 'three': 320},
             3: {'One': 130, 'Two': 230, 'three': 330}}

need to print as CSV in this order

'',1,2,3
One,110,120,130
Two,210,220,230
Three,310,320,330

No idea how to do it spent hours trying totally exhausted. I need pure python solution without using Numpy Transpose, Itertools etc

2

There are 2 best solutions below

0
SIGHUP On BEST ANSWER

There are numerous ways to do this. The simplest is probably to create an intermediate dictionary.

Something like this:

data_dict = {1: {'One': 110, 'Two': 210, 'three': 310},
             2: {'One': 120, 'Two': 220, 'three': 320},
             3: {'One': 130, 'Two': 230, 'three': 330}}

temp_dict = {"''": list(data_dict.keys())}

for value in data_dict.values():
    for k, v in value.items():
        temp_dict.setdefault(k, []).append(v)

for k, v in temp_dict.items():
    print(k, *v, sep=",")

Output:

'',1,2,3
One,110,120,130
Two,210,220,230
three,310,320,330
1
V Z On

You can use pandas

import pandas as pd

data_dict = {1: {'One': 110, 'Two': 210, 'three': 310},
             2: {'One': 120, 'Two': 220, 'three': 320},
             3: {'One': 130, 'Two': 230, 'three': 330}}

data = pd.DataFrame(data_dict)
data.to_csv('data.csv')
print(data)

output

         1    2    3
One    110  120  130
Two    210  220  230
three  310  320  330