我有一本字典:

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

我想把它打印出来,这样它就可以很好地与页眉对齐.我是否可以将标题添加到字典中,并始终确保它们位于顶部?

例子:

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.

推荐答案

你可以使用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)

或者,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 

Python-3.x相关问答推荐

字符串块数组:如何根据一个数组中的元素对另一个数组中的元素进行分组

如何在选中项目时设置QTreeView中整行的 colored颜色 ?

如何将多个字典合并到一个列中,并为不同的行使用相同的键

如何计算累积几何平均数?

匹配语句NaN

在Pandas中,根据另一列中的重复值将数据分组为一列

通过 Pandas 通过用户定义函数重命名数据框列

根据按不同列中的值分组的平均值划分 DataFrame

在 string.find() 条件下加入两个 Dataframes

使用 NaN 计算 pct_change 时如何避免 bfill 或 ffill

如何沿单列获取嵌套列表中的唯一值?

使用 Python 截断并重新编号对应于特定 ID/组的列

过滤阈值大小数据以使用 Pyspark 或 Python 读取

使用 OpenCV 从图像中减go 一条线

在python中将字符串写入文本文件

Python 3 `str.__getitem__` 的计算复杂度是多少?

将字符串表示与使用整数值的枚举相关联?

如何判断一个字符串是否包含有效的 Python 代码

为什么在 Python 中不推荐使用 MutableString?

新项目:Python 2 还是 Python 3?