sorting - Sort a nested dictionary in Python -
i have following dictionary.
var = = { '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 sort based on price
. resulting dictionary 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}, }
construct ordereddict
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 same.)
Comments
Post a Comment