打印字典之间的格式间距

时间:2016-12-05 20:43:42

标签: python dictionary printing format alignment

我试图从文件中的信息打印菜单,所以我获取了信息并创建了一个字典。我试图找出是否有办法格式化值之间的间距,因此我可以将值与标题对齐。我也试图找出是否存在每个键及其值将在中间没有一行空格的情况下打印。 我的代码目前看起来像这样:

#import classes
import inventory


#define constant for file
INVENTORY = "inventory.txt"

#define main
def main():
    #create empty dictionary to fill later
    inventory_dict = {}
    #call function to process inventory
    process_inventory(inventory_dict)
    #call function to print menu
    menu(inventory_dict)


#define process file inventory function
def process_inventory(inventory_dict):

    #open inventory file
    inventory_file = open(INVENTORY, 'r')

    #create inventory instances
    for item in inventory_file:

        #split line to reash
        inventory_list = item.split(",")

        #create variables to store each quality
        item_id = inventory_list[0]
        item_name = inventory_list[1]
        item_qty = inventory_list[2]
        item_price = inventory_list[3]

        #create object
        product = inventory.Inventory(item_id,item_name,item_qty,item_price)

        #add qualities to inventory dictionary
        inventory_dict[item_id] = product

    #close file
    inventory_file.close()

#define function to print menu
def menu(inventory_dict):
    #print headers
    print("ID Item Price Qty Avaliable")

    #print object information
    for object_id in inventory_dict:
        print(inventory_dict[object_id])

    #print how to exit
    print("Enter 0 when finished")

    #print blank line
    print(" ")

打印字典时输出如下:

Output

为什么它打印前两个键的值一行一行没有空格但其他键之间有一行?我想将每个值与它的标题对齐。那可能吗?如果是这样的话?我能想到的唯一方法是使用print函数并自己格式化。

1 个答案:

答案 0 :(得分:0)

他们不对齐的原因是因为每个项目的长度不同。每行中的第一项将更长的时间推到下一个项目。

这是修复此问题的menu函数的修改版本:

def menu(inventory_dict):
    maxLength = 0
    for row in inventory_dict.values():
        for item in row.values():
            maxLength = max(len(item), maxLength) # If the item is longer than our current longest, make it the longest
    #print headers
    for header in ("ID", "Item", "Price", "Qty", "Avaliable"):
        print(header.ljust(maxLength)) # Fill spaces in until the header is as long as our longest item
    print()

    #print object information
    for row in inventory_dict.values():
        for item in row.values():
            print(item.ljust(maxLength)) # Fill spaces in until the header is as long as our longest item

    #print how to exit
    print("Enter 0 when finished")

    #print blank line
    print()

我无法验证它是否有效,因为我没有inventory模块。