【问题标题】:Creating table from dictionary & string formatting - Python [duplicate]从字典和字符串格式创建表 - Python [重复]
【发布时间】:2020-12-17 16:10:17
【问题描述】:

基本上,我有一本字典,我想从中构造一个表。

字典的格式为:

dict={
'1':{'fruit':'apple',
     'price':0.60,
     'unit':'pieces',
     'stock':60
},
'2':{'fruit':'cherries',
     'price':15.49,
     'unit':'kg',
     'stock':5.6
},
and so on.
}

我希望表格看起来像数字正确对齐:

no  |item      | price |   stock
----+----------+-------+----------
1   |apple     |  0.60 | 60 pieces
----+----------+-------+----------
2   |cherries  | 15.49 |  5.6 kg

and so on...

我确实想打印这张表,我正在尝试编写一个函数,将 dict 作为输入,RETURNS 将此表作为字符串。

这是我的尝试:

def items(dct)
table="{0:<2} | {1:<33} | {2:^8} | {3:^11}".format("no", "item", "price","stock") 
...
return table

我在格式化字符串时遇到了问题,我尝试添加换行符并尝试不同的东西,但我总是遇到各种错误,而且事情没有解决:( 我是Python新手,有人可以教育我吗? 谢谢!

【问题讨论】:

  • 但我总是遇到各种错误,而且事情就是不正常向我们展示错误,并向我们展示你得到的输出。

标签: python string dictionary formatting


【解决方案1】:
def table_create(dct):
    dashes = "{0:<2} + {1:<33} + {2:^8} + {3:^11} \n".format("-"*2, "-"*33, "-"*8, "-"*11)
    table="{0:<2} | {1:<33} | {2:^8} | {3:^11} \n".format("no", "item", "price", "stock")
    table+=dashes
    for key, value in dct.items():
        table+="{0:<2} | {1:<33} | {2:^8} | {3:^11} \n".format(key, value["fruit"], value["price"],str(value["stock"])+" "+value["unit"]) 
        table+=dashes
    return table

print(table_create(dct))

# output
no | item                              |  price   |    stock    
-- + --------------------------------- + -------- + ----------- 
1  | apple                             |   0.6    |  60 pieces  
-- + --------------------------------- + -------- + ----------- 
2  | cherries                          |  15.49   |   5.6 kg    
-- + --------------------------------- + -------- + ----------- 

【讨论】:

  • 啊,完美,我没想到将表格分成几个部分并使用 for 循环。非常感谢!
【解决方案2】:

与存储表头的方式相同,您可以存储其条目并打印它们或做任何您想做的事情。

    dict={
    '1':{'fruit':'apple','price':0.60,'unit':'pieces','stock':60},
    '2':{'fruit':'cherries','price':15.49,'unit':'kg','stock':5.6}
    }
    
    def items(dct):
        table="{0:<2} | {1:<33} | {2:^8} | {3:^11}".format("no", "item", "price","stock") 
        print(table)
        for i in dict:
            print("{0:<2} | {1:<33} | {2:^8} | {3:^11}".format(i,dict[i]['fruit'] ,dict[i]['price'],str(dict[i]['stock'])+' '+dict[i]['unit']))

items(dict)

【讨论】:

    【解决方案3】:

    您可以检查以下问题:

    Python - Printing a dictionary as a horizontal table with headers

    Printing Lists as Tabular Data

    不用打印数据,只需将其连接成一个字符串。

    【讨论】:

      猜你喜欢
      • 2020-12-05
      • 1970-01-01
      • 2023-03-11
      • 2020-03-17
      • 1970-01-01
      • 2016-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多