views:

269

answers:

3

How to sort the following dictionary by the value of "remaining_pcs" or "discount_ratio"?

promotion_items = {
    'one': {'remaining_pcs': 100, 'discount_ratio': 10},
    'two': {'remaining_pcs': 200, 'discount_ratio': 20},
}

EDIT

What I mean is getting a sorted list of above dictionary, not to sort the dictionary itself.

+2  A: 

Please see To sort a dictionary:

Dictionaries can't be sorted -- a mapping has no ordering! -- so, when you feel the need to sort one, you no doubt want to sort its keys (in a separate list).

Andrew Hare
A: 

If 'remaining_pcs' and 'discount_ratio' are the only keys in the nested dictionaries then:

result = sorted(promotion_items.iteritems(), key=lambda pair: pair[1].items())

If there could be other keys then:

def item_value(pair):
    return pair[1]['remaining_pcs'], pair[1]['discount_ratio']
result = sorted(promotion_items.iteritems(), key=item_value)
J.F. Sebastian
+5  A: 

You can only sort the keys (or items or values) of a dictionary, into a separate list (as I wrote years ago in the recipe that @Andrew's quoting). E.g., to sort keys according to your stated criteria:

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)
Alex Martelli
For the second `def bypcs` I suppose you meant `def bydra`?
unutbu
@unutbu, right, and I see Mike Graham has already edited my A to fix this (tx both!).
Alex Martelli