Faller Faller - 1 month ago 15
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().

Example:

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.

Answer

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)

Output:

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