3
我有一个像这样构造的字典列表。Python按值排序深层嵌套字典列表
[
{
'id': 1,
'last_message': {
'sent_at': '2015-10-15T17:48:52.515Z',
'...' : '...'
},
'...' : '...',
},
{
'id': 2,
'last_message': {
'sent_at': '2015-10-15T17:45:52.515Z',
'...' : '...'
},
'...' : '...',
},
{
'id': 3,
'last_message': {
'sent_at': '2015-10-15T17:43:52.515Z',
'...' : '...'
},
'...' : '...',
}
]
并且想按['last_message']['sent_at']
对列表进行排序。
我试图做一个像这样的插入排序,但这会导致无限循环。
ret = []
for conversation in conversations:
if len(ret) > 1:
for conv in ret:
if conversation['last_message']['sent_at'] > conv['last_message']['sent_at']:
ret.insert(ret.index(conv), conversation)
continue
else:
ret.append(conversation)
我该怎么做才能做到这一点?
你不推倒重来。你想要的是[关键功能](https://wiki.python.org/moin/HowTo/Sorting#Key_Functions)和Python的本地'sort'。 –
[排序列表的字典](http://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-values-of-the-dictionary-in-python) – sam