Sorting Python dictionary based on nested dictionary values

后端 未结 2 1277
予麋鹿
予麋鹿 2020-12-13 20:23

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<

相关标签:
2条回答
  • 2020-12-13 20:31

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

    0 讨论(0)
  • 2020-12-13 20:50
    >>> 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})])
    
    0 讨论(0)
提交回复
热议问题