Python - 将字典打印为带有标题的水平表 [英] Python - Printing a dictionary as a horizontal table with headers
问题描述
我有一本字典:
import math
import random
d = {1: ["Spices", math.floor(random.gauss(40, 5))],
2: ["Other stuff", math.floor(random.gauss(20, 5))],
3: ["Tea", math.floor(random.gauss(50, 5))],
10: ["Contraband", math.floor(random.gauss(1000, 5))],
5: ["Fruit", math.floor(random.gauss(10, 5))],
6: ["Textiles", math.floor(random.gauss(40, 5))]
}
我想把它打印出来,让它与标题很好地对齐.我可以将标题添加到字典中并始终确保它们排在最前面吗?我已经看到了几种垂直执行的方法,但我希望它的最大列宽接近最大 str() 或 int().
I want to print it out so it lines up nicely with headers. Can I add the headers to the dictionary and always be sure they come out on top? I've seen a few ways to do it vertically but I'd like to have it come out with max column widths close to the max str() or int().
示例:
密钥____________________标签______________________编号
1____________香料___________42
2______________________其他内容_____________16
等
Key___________________Label______________________Number
1______________________Spices_____________________42
2______________________Other Stuff_____________16
etc
显然我什至无法在此编辑器中手动执行此操作,但我希望这个想法能够实现.我也真的不想要__.只是一个占位符.
谢谢大家.
Apparently I can't even do this inside of this editor manually, but I hope the idea comes across.
I also don't really want the __ either. Just a place holder.
Thanks all.
推荐答案
您可以使用 python2 中的字符串格式:
print "{:<8} {:<15} {:<10}".format('Key','Label','Number')
for k, v in d.iteritems():
label, num = v
print "{:<8} {:<15} {:<10}".format(k, label, num)
或者,python3 中的字符串格式:
print("{:<8} {:<15} {:<10}".format('Key','Label','Number'))
for k, v in d.items():
label, num = v
print("{:<8} {:<15} {:<10}".format(k, label, num))
输出:
Key Label Number
1 Spices 38.0
2 Other stuff 24.0
3 Tea 44.0
5 Fruit 5.0
6 Textiles 37.0
10 Contraband 1000.0
这篇关于Python - 将字典打印为带有标题的水平表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!