简体   繁体   中英

Python sorting a list of deeply nested dictionaries by value

I have a list of dictionaries structured like so.

[
    {
        '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',
            '...' : '...'
        },
        '...' : '...',
    }
]

And want to sort the list by ['last_message']['sent_at'] .

I tried to do an insertion sort like this, but this results in an infinite loop.

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)

What can I do to achieve this?

You can simply use sorted() method with key argument to sort the list of dictionaries.

Also, I would recommend actually converting the string to datetime object before passing it to the key argument using datetime.datetime.strptime() .

Example -

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

Demo -

>>> 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'}}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM