2016-04-21 36 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)) 
相關問題