Python - 将字典打印为具有标题的水平表 [英] Python - Printing a dictionary as a horizontal table with headers
问题描述
我有一个字典:
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().
示例:
Key_ _ __ _ __ _ 强> 标签的 _ __ _ __ _ ___ 强> 号码
1 _ __ _ __ _ ___ em>香料 _ __ _ __ _ __ 42
2 _ __ _ __ _ ___ 其他东西 _ ____ _16
etc
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.
推荐答案
您可以使用字符串格式:
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)
输出:
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屋!