如何按键订购字典并将其打印到 table

How to order a dictionary by key and print it into a table

我在另一个字典中有一个字典,即我有一个库存字典(如超市),其中包含具有名称、数量等的产品(如苹果)字典。我需要按键对其进行排序,将其打印为 table.

目前我有,

stock = load_stock_from_file() 
print("{0} | {1:<35} | {2:^11} | {3:^12} ".format("Ident", "Product", "Price", "Amount"))
print("-" * 6 + "+" + "-"*37+"+"+"-"*13+"+"+"-"*12)

for key in sorted(stock):
print("{name:<35} | {price:^11} | {amount:^12} ".format(**key))

这就是我想要的(下图),但我收到错误 'TypeError: format() argument after ** must be a mapping, not str'

Ident | Product                             |   Price   |   Amount
-------+-------------------------------------+-----------+-------------
10000 | Granny Smith Apples Loose           |    0.32 £ |    6 pieces
10001 | Watermelon Fingers 90G              |    0.50 £ |   17 pieces
10002 | Mango And Pineapple Fingers 80G     |    0.50 £ |    2 pieces
10003 | Melon Finger Tray 80G               |    0.50 £ |   10 pieces
10004 | Bananas Loose                       |    0.68 £ |    2.2 kg
10005 | Conference Pears Loose              |    2.00 £ |    1.6 kg

我的键是 10000 个数字,其余是该字典的一部分。

谢谢。

该错误表明您的键变量是一个 str。我猜你需要格式化值而不是元素。你可以试试:

for key in sorted(stock):
    print("{name:<35} | {price:^11} | {amount:^12} ".format(**stock[key]))

您正在将键(它是一个字符串)传递给格式化方法,在这种情况下,由于双星,它需要一个字典。您只需要在循环中将 key 替换为 stock[key] 即可。

这里还有format_map字符串的方法可以用,那就不用解包双星字典了。

for key in sorted(stock):
    print(key, end='   ')
    print("{name:<35} | {price:^11} | {amount:^12} ".format_map(stock[key]))

如果您想按价格或其他值排序,您可以这样做:

for ident, dicti in sorted(stock.items(), key=lambda item: item[1]['price']):
    print(ident, end='   ')
    print("{name:<35} | {price:^11} | {amount:^12} ".format_map(dicti))