Python - Printing a dictionary as a horizontal table with headers

前端 未结 6 571
花落未央
花落未央 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:29

    String formatting provides a nice, simple solution. This answer is an update for Python 3 of the nice answer from @Ashwini.

    str_fmt = "{:<8} {:<15} {:<10}"
    print(str_fmt.format('Key','Label','Number'))
    for k, v in d.items():
        label, num = v
        print(str_fmt.format(k, label, num))
    

提交回复
热议问题