2010-03-10 135 views
4

如何用「remaining_pcs」或「discount_ratio」的值對以下字典進行排序?用Python中的字典中的字典鍵排序

promotion_items = { 
    'one': {'remaining_pcs': 100, 'discount_ratio': 10}, 
    'two': {'remaining_pcs': 200, 'discount_ratio': 20}, 
} 

編輯

我的意思是讓上面字典的排序列表,不排序的字典本身。

+4

你不能排序字典。 – 2010-03-10 05:38:13

回答

5

您可以將鍵唯一排序 (或項目或價值)的字典,成一個單獨的列表(正如我多年前在@安德魯引用的配方中所寫的那樣)。例如,按照你陳述的標準對鍵進行分類:

promotion_items = { 
    'one': {'remaining_pcs': 100, 'discount_ratio': 10}, 
    'two': {'remaining_pcs': 200, 'discount_ratio': 20}, 
} 
def bypcs(k): 
    return promotion_items[k]['remaining_pcs'] 
byrempcs = sorted(promotion_items, key=bypcs) 
def bydra(k): 
    return promotion_items[k]['discount_ratio'] 
bydiscra = sorted(promotion_items, key=bydra) 
+0

對於第二個'def bypcs',我想你的意思是'def bydra'? – unutbu 2010-03-10 06:02:13

+0

@unutbu,對,我看到邁克格雷厄姆已經編輯我的A來修復這個問題(tx既!)。 – 2010-03-10 06:50:53

2

請參閱To sort a dictionary

詞典不能進行排序 - 一個 映射沒有訂購! - 所以,當你覺得需要排序的時候,你沒有 懷疑要對它的鍵進行排序(在 單獨的列表中)。

0

如果'remaining_pcs''discount_ratio'是嵌套詞典唯一的按鍵,然後:

result = sorted(promotion_items.iteritems(), key=lambda pair: pair[1].items()) 

如果有可能是其他按鍵則:

def item_value(pair): 
    return pair[1]['remaining_pcs'], pair[1]['discount_ratio'] 
result = sorted(promotion_items.iteritems(), key=item_value)