Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
539 views
in Technique[技术] by (71.8m points)

Python - Printing a dictionary as a horizontal table with headers

I have a dictionary:

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use string formatting in 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)

Or, string formatting in 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))

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 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...