mypointis
mypointis

Reputation: 38

Rearrange the output of a dictionary (Python)

I have the following code:

dic = {'key1': [0, 0, 0], 'key2': [1, 1, 1], 'key3': [2, 2, 2]}

keys = dic.keys()
values = dic.values()

for i in range(0, len(keys)):
    print keys[i]
    for j in range(0, len(values)):
        print values[i][j]

The output that it produces is the following:

key3
2
2
2
key2
1
1
1
key1
0
0
0

What I would like to have is the following output:

key3 key2 key1
2    1    0
2    1    0
2    1    0

Thanks a lot!

Upvotes: 1

Views: 446

Answers (6)

dawg
dawg

Reputation: 103874

You could do something like this:

dic = {'key1': [0, 0, 0], 'key2': [1, 1, 1], 'key3': [2, 2, 22222]}

def printTable (tbl, borderHorizontal = '-', borderVertical = '|', borderCross = '+'):
    cols = [list(x) for x in zip(*tbl)]
    lengths = [max(map(len, map(str, col))) for col in cols]
    f = borderVertical + borderVertical.join(' {:>%d} ' % l for l in lengths) + borderVertical
    s = borderCross + borderCross.join(borderHorizontal * (l+2) for l in lengths) + borderCross

    print(s)
    for row in tbl:
        print(f.format(*row))
        print(s)

sorted_keys=sorted(dic.keys(),reverse=True)
table=[sorted_keys]
for row in zip(*[dic[k] for k in sorted_keys]):
    table.append(list(row))

printTable(table) 

Prints

+-------+------+------+
|  key3 | key2 | key1 |
+-------+------+------+
|     2 |    1 |    0 |
+-------+------+------+
|     2 |    1 |    0 |
+-------+------+------+
| 22222 |    1 |    0 |
+-------+------+------+

Upvotes: 0

Inbar Rose
Inbar Rose

Reputation: 43447

This does it.

dic = {'key1': [0, 0, 0], 'key2': [1, 1, 1], 'key3': [2, 2, 2]}

keys = sorted(dic.keys(), reverse=True)
values = [map(str, dic[k]) for k in keys]

print '\t'.join(keys)
print '\n'.join(['\t'.join(v) for v in zip(*values)])

Output:

>>> 
key3    key2    key1
2       1       0
2       1       0
2       1       0

Upvotes: 0

Roberto
Roberto

Reputation: 2786

Oh wait I misunderstood the question, let me edit.

See if you like it:

dic = {'key1': [0, 0, 0], 'key2': [1, 1, 1], 'key3': [2, 2, 2]}

keys = dic.keys()
values = dic.values()
spacing = '{:<8}'
print ''.join(map(str, [spacing.format(element) for element in keys]))
for i in range(len(values)):
    print ''.join(map(str, [spacing.format(element) for element in values[i]]))

Upvotes: 0

Pedro Werneck
Pedro Werneck

Reputation: 41908

Assuming all lists of values have the same length and keys has the order you want for the headers, this should do it:

print '\t'.join(keys)
for row in zip(*[dic[k] for k in keys]):
    print '\t'.join(map(str, row))

Update

I used the list comprehension to guarantee the ordering, but according to Python documentation, dict.keys() and dict.values() ordering is guaranteed if the dictionary isn't changed in between. Considering that, the list comprehension above can be removed and the code can be as simple as:

print '\t'.join(keys)
for row in zip(*values):
    print '\t'.join(map(str, row))

Upvotes: 2

user2497586
user2497586

Reputation:

You want to use string.join, the docs of which can be found here string docs. So, you can print out all of your keys using this line:

print " ".join(keys)

This will output key3 key2 key1

You can do the same thing for your values lists. However, you might want to change the values list into all string with this line:

values[:] = [[str(x) for x in y] for y in values]

Then, since they're all string, you can perform the string.join() on them.

Upvotes: 0

amiller27
amiller27

Reputation: 506

Rearrange your loops to look like this:

for i in range(len(keys)):
    print keys[i],
print
for line in range(len(values)):
    for column in range(len(keys)):
        print values[column][line], '  ',#change the number of spaces to get the right fit
    print

Upvotes: 0

Related Questions