小编典典

根据嵌套字典值对Python字典进行排序

python

如何根据嵌套字典的内部值对Python字典进行排序?

例如,mydict根据以下值排序context

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

结果应该是这样的:

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

阅读 155

收藏
2020-12-20

共1个答案

小编典典

>>> 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})])
2020-12-20