Faller Faller - 1 year ago 129
Python Question

Python - Printing a dictionary as a horizontal table with headers

I have a dictionary:

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

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




__________Other Stuff______16


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.

Answer Source

You can use string formatting:

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 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download