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}       
}
1
  • 1
    Do you want a list output? or a dictionary output? Commented Aug 1, 2012 at 6:34

1 Answer 1

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})])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.