我有以下代码:
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]
它产生的输出如下:
key3
2
2
2
key2
1
1
1
key1
0
0
0
我想要的是以下输出:
key3 key2 key1
2 1 0
2 1 0
2 1 0
非常感谢!
答案 0 :(得分:2)
假设所有值列表都具有相同的长度且keys
具有您想要的标题顺序,那么应该这样做:
print '\t'.join(keys)
for row in zip(*[dic[k] for k in keys]):
print '\t'.join(map(str, row))
<强>更新强>
我使用list comprehension来保证排序,但是根据Python documentation,如果字典之间没有更改,则保证dict.keys()和dict.values()顺序。考虑到这一点,可以删除上面的列表理解,代码可以简单如下:
print '\t'.join(keys)
for row in zip(*values):
print '\t'.join(map(str, row))
答案 1 :(得分:0)
看看你是否喜欢它:
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]]))
答案 2 :(得分:0)
重新排列循环,如下所示:
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
答案 3 :(得分:0)
您想使用string.join,其文档可在此处找到string docs。因此,您可以使用以下行打印出所有密钥:
print " ".join(keys)
这将输出key3 key2 key1
您可以为值列表执行相同的操作。但是,您可能希望使用以下行将值列表更改为所有字符串:
values[:] = [[str(x) for x in y] for y in values]
然后,因为它们都是字符串,所以你可以对它们执行string.join()。
答案 4 :(得分:0)
你可以这样做:
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)
打印
+-------+------+------+
| key3 | key2 | key1 |
+-------+------+------+
| 2 | 1 | 0 |
+-------+------+------+
| 2 | 1 | 0 |
+-------+------+------+
| 22222 | 1 | 0 |
+-------+------+------+
答案 5 :(得分:0)
就是这样。
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)])
输出:
>>>
key3 key2 key1
2 1 0
2 1 0
2 1 0