如何根据嵌套字典的内部值对Python字典进行排序?
例如,mydict根据以下值排序context:
mydict
context
mydict = { 'age': {'context': 2}, 'address': {'context': 4}, 'name': {'context': 1} }
结果应该是这样的:
{ '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})])