3

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?

2
  • 5
    You don't reinvent the wheel. What you want is a key function and Python's native sort. Commented Oct 15, 2015 at 19:15
  • Sort list of dict Commented Oct 15, 2015 at 19:23

1 Answer 1

5

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'}}]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.