Python - Printing a dictionary as a horizontal table with headers

前端 未结 6 569
花落未央
花落未央 2020-12-02 19:01

I have a dictionary:

import math
import random

d = {1: ["Spices", math.floor(random.gauss(40, 5))],
    2: ["Other stuff", math.floor(ran         


        
6条回答
  •  时光说笑
    2020-12-02 19:31

    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 
    

提交回复
热议问题