jac*_*ack 4 python sorting dictionary
如何按"remaining_pcs"或"discount_ratio"的值对以下字典进行排序?
promotion_items = {
'one': {'remaining_pcs': 100, 'discount_ratio': 10},
'two': {'remaining_pcs': 200, 'discount_ratio': 20},
}
Run Code Online (Sandbox Code Playgroud)
编辑
我的意思是获取上面字典的排序列表,而不是排序字典本身.
您只能将字典的键(或项目或值)排序到单独的列表中(正如我多年前在@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)
Run Code Online (Sandbox Code Playgroud)