Python中字典内字典的按键排序

Python中字典内字典的按键排序,python,dictionary,sorting,Python,Dictionary,Sorting,如何根据“剩余PC”或“折扣率”的值对以下字典进行排序 编辑 我的意思是获取上述词典的排序列表,而不是对词典本身进行排序。请参见: 字典无法排序--a 映射没有顺序!——那么,什么时候 你觉得有必要对一个进行分类,不是吗 疑团想把它的钥匙分类(在 单独列表) 如果嵌套字典中只有“剩余”和“折扣率”键,则: result = sorted(promotion_items.iteritems(), key=lambda pair: pair[1].items()) 如果可能有其他钥匙,则: def

如何根据“剩余PC”或“折扣率”的值对以下字典进行排序

编辑

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

请参见:

字典无法排序--a 映射没有顺序!——那么,什么时候 你觉得有必要对一个进行分类,不是吗 疑团想把它的钥匙分类(在 单独列表)


如果嵌套字典中只有
“剩余”和
“折扣率”
键,则:

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)
您只能将字典中的键(或项或值)排序到一个单独的列表中(正如我多年前在@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)

对于第二个
defbypcs
我想你的意思是
defbydra
?@unutbu,对吧,我看到迈克·格雷厄姆已经编辑了我的A来解决这个问题(tx和tx!)。
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)