2015-10-15 126 views
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) 

我该怎么做才能做到这一点?

+5

你不推倒重来。你想要的是[关键功能](https://wiki.python.org/moin/HowTo/Sorting#Key_Functions)和Python的本地'sort'。 –

+0

[排序列表的字典](http://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-values-of-the-dictionary-in-python) – sam

回答

5

您可以简单地使用sorted()方法和key参数对字典列表进行排序。

此外,我建议实际上将字符串转换为datetime对象,然后使用datetime.datetime.strptime()将它传递给关键参数。

示例 -

import datetime 
result = sorted(conversations, key=lambda x: datetime.datetime.strptime(x['last_message']['sent_at'],'%Y-%m-%dT%H:%M:%S.%fZ')) 

演示 -

>>> conversations = [ 
...  { 
...   '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', 
...    '...' : '...' 
...   }, 
...   '...' : '...', 
...  } 
... ] 
>>> 
>>> import datetime 
>>> result = sorted(conversations, key=lambda x: datetime.datetime.strptime(x['last_message']['sent_at'],'%Y-%m-%dT%H:%M:%S.%fZ')) 
>>> pprint.pprint(result) 
[{'...': '...', 
    'id': 3, 
    'last_message': {'...': '...', 'sent_at': '2015-10-15T17:43:52.515Z'}}, 
{'...': '...', 
    'id': 2, 
    'last_message': {'...': '...', 'sent_at': '2015-10-15T17:45:52.515Z'}}, 
{'...': '...', 
    'id': 1, 
    'last_message': {'...': '...', 'sent_at': '2015-10-15T17:48:52.515Z'}}]