【发布时间】:2015-10-15 19:12:55
【问题描述】:
我有一个这样结构的字典列表。
[
{
'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)
我能做些什么来实现这个目标?
【问题讨论】:
-
您无需重新发明轮子。你想要的是 key function 和 Python 原生的
sort。
标签: python list sorting dictionary