在Python中对字典内的字典按键进行排序

4
如何按“remaining_pcs”或“discount_ratio”的值对以下字典进行排序?
promotion_items = {
    'one': {'remaining_pcs': 100, 'discount_ratio': 10},
    'two': {'remaining_pcs': 200, 'discount_ratio': 20},
}

编辑

我的意思是获取上述字典的排序列表,而不是对字典本身进行排序。

3个回答

5

您只能对字典的(或项目或值)进行排序,并将其排序为单独的列表(正如我多年前在配方中所写的,@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)

第二个 def bypcs,我想你是指 def bydra 吧? - unutbu
@unutbu,没错,我看到Mike Graham已经编辑我的A来解决这个问题(感谢两位!)。 - Alex Martelli

2
请参见如何对字典进行排序
字典是无法排序的--映射没有顺序!--因此,当您需要对其进行排序时,无疑是想要对其键进行排序(在单独的列表中)。

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接