Python Dicts inside List inside Dict – sorting possible?

  python, python-3.x

I have an object in Python 3 of this format:

a = {
        'events': [
            {
                'timestamp': 30,
                'message': 'test'
            },
            {
                'timestamp': 10,
                'message': 'foo'
            },
            {
                'timestamp': 20,
                'message': 'testbar'
            },
        ],
        'first': 'abc',
        'last': 'def'
    }

I’d like to sort each dict in events by the timestamp key. For example, an ascending sort on the object should hopefully give:

a = {
        'events': [
            {
                'timestamp': 10,
                'message': 'foo'
            },
            {
                'timestamp': 20,
                'message': 'testbar'
            },
            {
                'timestamp': 30,
                'message': 'test'
            },
        ],
        'first': 'abc',
        'last': 'def'
    }

I’ve tried a lambda sort with something like:

a['events'].sort(key=lambda event : event['timestamp'])

But this gives me a KeyError: 'timestamp'

Source: Python-3x Questions

LEAVE A COMMENT