2016-04-21 37 views
1

我在另一个字典里面有一本字典ie我有一个包含产品字典(如苹果)的库存字典(如超市),它们的名称,数量等我需要按键排序并将其打印为表格。如何通过密钥订购字典并将其打印到表格

目前我有,

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

这就是我想要的(如下图),但我得到的错误 '类型错误:格式()参数**后必须是一个映射,而不是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个数字,其余的都是该字典的一部分。

感谢。

回答

2

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

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

你将密钥(这是一个字符串)传递给在这种情况下期望字典的格式方法,因为双星。您只需在循环中将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)) 
相关问题