简体   繁体   中英

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!

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))

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]]))

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

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.

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 |
+-------+------+------+

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM