Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a nested dictionary in Python

I have the following dictionary.

var = a = { 
  'Black': { 'grams': 1906, 'price': 2.05},
  'Blue': { 'grams': 9526, 'price': 22.88},
  'Gold': { 'grams': 194, 'price': 8.24},
  'Magenta': { 'grams': 6035, 'price': 56.69},
  'Maroon': { 'grams': 922, 'price': 18.76},
  'Mint green': { 'grams': 9961, 'price': 63.89},
  'Orchid': { 'grams': 4970, 'price': 10.78},
  'Tan': { 'grams': 6738, 'price': 50.54},
  'Yellow': { 'grams': 6045, 'price': 54.19}
}

How can I sort it based on the price. So the resulting dictionary will look like below.

result = { 
  'Black': { 'grams': 1906, 'price': 2.05},
  'Gold': { 'grams': 194, 'price': 8.24},
  'Orchid': { 'grams': 4970, 'price': 10.78},
  'Maroon': { 'grams': 922, 'price': 18.76},
  'Blue': { 'grams': 9526, 'price': 22.88},
  'Tan': { 'grams': 6738, 'price': 50.54},
  'Magenta': { 'grams': 6035, 'price': 56.69},
  'Mint green': { 'grams': 9961, 'price': 63.89}, 
}
like image 1000
Pattu Avatar asked Mar 19 '26 16:03

Pattu


1 Answers

Construct an OrderedDict from a list of ordered item tuples:

from collections import OrderedDict

ordered = OrderedDict(sorted(a.items(), key=lambda i: i[1]['price']))

(.items() assumes Python 3, in Python 2 iteritems should do the same.)

like image 125
deceze Avatar answered Mar 22 '26 05:03

deceze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!