Sorting by dictionary key inside a dictionary in Python

How to sort the next dictionary by the value "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 to get a sorted list above the dictionary, and not sort the dictionary itself.

+4
source share
3 answers

You can sort the keys (or elements or values) of the dictionary into a separate list (as I wrote many years ago in the recipe quoting @Andrew). For example, to sort keys according to your 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) 
+5
source

See To sort a dictionary :

Dictionaries cannot be sorted - a mapping is out of order! - so when you feel the need to sort one, you have no doubt about the need to sort its keys (into a separate list).

+2
source

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

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

If there were other keys, then:

 def item_value(pair): return pair[1]['remaining_pcs'], pair[1]['discount_ratio'] result = sorted(promotion_items.iteritems(), key=item_value) 
0
source

Source: https://habr.com/ru/post/1303638/


All Articles