在Python中对字典内的字典按键排序
如何根据“remaining_pcs”或“discount_ratio”的值对下面这个字典进行排序呢?
promotion_items = {
'one': {'remaining_pcs': 100, 'discount_ratio': 10},
'two': {'remaining_pcs': 200, 'discount_ratio': 20},
}
补充说明
我想表达的是,想要得到一个排序后的列表,而不是直接对字典本身进行排序。
3 个回答
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)
2
请查看 如何对字典进行排序:
字典是不能排序的——因为字典里的内容没有顺序!所以,当你想要对字典进行排序时,实际上你是想要对它的键进行排序(并放在一个单独的列表里)。
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)