简体   繁体   中英

Sorting Python dictionary based on nested dictionary values

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}       
}
>>> 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})])

You can not sort a dictionary no matter how hard you try, because they are an unordered collection. Use OrderedDict form collections module instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM