23

ネストされた辞書の内部値に基づいて Python 辞書をどのようにソートしますか?

たとえばmydict、 の値に基づいて以下を並べ替えcontextます。

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

結果は次のようになります。

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

1 に答える 1

20
>>> 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})])
于 2012-08-01T06:31:10.687 に答える