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

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

configurationsection - activeMq-5.13.3 setup configurations for wildfly 10.0.0 -