24

How do you sort a Python dictionary based on the inner value of a nested dictionary?

For example, sort mydict below based on the value of context:

mydict = {
    'age': {'context': 2},
    'address': {'context': 4},
    'name': {'context': 1}
}

The result should be like this:

{
    'name': {'context': 1}, 
    'age': {'context': 2},
    'address': {'context': 4}       
}
Ghopper21
  • 10,287
  • 10
  • 63
  • 92
Regal Paris
  • 339
  • 5
  • 12

1 Answers1

21
>>> from collections import OrderedDict
>>> mydict = {
        'age': {'context': 2},
        'address': {'context': 4},
        'name': {'context': 1}
}
>>> OrderedDict(sorted(mydict.iteritems(), key=lambda x: x[1]['context']))
OrderedDict([('name', {'context': 1}), ('age', {'context': 2}), ('address', {'context': 4})])
jamylak
  • 128,818
  • 30
  • 231
  • 230