1

I have a python dictionary, for example:

 my_dict = {100: {0.5: 1, 0.6: 0}, 200: {0.5: 1, 0.6: 1}}

i.e., the it is a dictionary of dictionaries.

I would like to print it as a matrix, like this:

     0.5, 0.6
100  1    0
200  1    1

I wanted to use something like this: Python - Printing a dictionary as a horizontal table with headers

but the problem is that I don't know the size of either the dictionary (how many keys it has), or the sub-dictionary...

Community
  • 1
  • 1
Cheshie
  • 2,777
  • 6
  • 32
  • 51

2 Answers2

2

Here's a solution that first builds a set of all columns and then uses that as template for every row. The upside of this solution is that you only need to include the data sets you want in every dict. To display that the input in this example introduces a row "300" with one intersecting column and a new one.

The OrderedDict is a small helper for ordering columns. You could also loop if you don't like the dependency.

from collections import OrderedDict

my_dict = {
100: {0.5: 1, 0.6: 0         },
200: {0.5: 1, 0.6: 1         },
300: {0.5: 5,         0.7: 6}}

# header columns
cols = set()
for d in my_dict.values():
    cols.update(d.keys())
cols = list(sorted(cols))
print "\t", "\t".join([str(c) for c in cols])

# data rows
for row, d_cols in sorted(my_dict.items()):
    e_cols = OrderedDict().fromkeys(cols)
    e_cols.update(d_cols)
    print row, "\t", "\t".join([str(v) for v in e_cols.values()])

Result:

python test.py 

        0.5     0.6     0.7
100     1       0       None
200     1       1       None
300     5       None    6
Hubert Grzeskowiak
  • 15,137
  • 5
  • 57
  • 74
1

You could use pandas

import pandas as pd

my_dict = {100: {0.5: 1, 0.6: 0}, 200: {0.5: 1, 0.6: 1}}

df = pd.DataFrame(my_dict)

print df

     100 200
0.5  1   1
0.6  0   1


print df.T

     0.5, 0.6
100  1    0
200  1    1
furas
  • 134,197
  • 12
  • 106
  • 148