Reg*_*ris 17 python sorting dictionary
如何根据嵌套字典的内部值对Python字典进行排序?
例如,mydict根据以下值排序context:
mydict = {
'age': {'context': 2},
'address': {'context': 4},
'name': {'context': 1}
}
Run Code Online (Sandbox Code Playgroud)
结果应该是这样的:
{
'name': {'context': 1},
'age': {'context': 2},
'address': {'context': 4}
}
Run Code Online (Sandbox Code Playgroud)
jam*_*lak 18
>>> 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})])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7285 次 |
| 最近记录: |