簡體   English   中英

在Python中的字典內按字典鍵排序

[英]Sort by key of dictionary inside a dictionary in Python

如何按“remaining_pcs”或“discount_ratio”的值對以下字典進行排序?

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

編輯

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

您只能將字典的 (或項目或值)排序到單獨的列表中(正如我多年前在@Andrew引用的配方中所寫的那樣)。 例如,根據您所述的標准對密鑰進行排序:

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)

請參閱排序字典

字典無法排序 - 映射沒有排序! - 所以,當你覺得需要對它進行排序時,你無疑要對其鍵進行排序(在單獨的列表中)。

如果'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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM