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