xbgxtmp
xbgxtmp

Reputation: 13

Sort dictionary by dict value

I have such dict:

resp = {'1366451044687880192': {'created_at': 'Mon Mar 01 18:11:31 +0000 2021', 'id': 1366463640451233323}, '1366463640451256323': {'created_at': 'Mon Mar 05 19:01:34 +0000 2021', 'id': 1366463640451256323}}

Is it possible to sort it by created_at value?

Tried but doesnt work:

sorted(resp.values(), key=lambda item: item[0]['created_at'])

Upvotes: 1

Views: 94

Answers (1)

Arty
Arty

Reputation: 16747

Try it online!

resp = {
    '1366451044687880192': {
        'created_at': 'Mon Mar 01 18:11:31 +0000 2021',
        'id': 1366463640451233323
    },
    '1366463640451256323': {
        'created_at': 'Mon Mar 05 19:01:34 +0000 2021',
        'id': 1366463640451256323
    }
}
print(sorted(resp.values(), key=lambda item: item['created_at']))

Output:

[
    {'created_at': 'Mon Mar 01 18:11:31 +0000 2021', 'id': 1366463640451233323},
    {'created_at': 'Mon Mar 05 19:01:34 +0000 2021', 'id': 1366463640451256323}
]

Or you can sort key-values (items) through (Try it online!):

sorted(resp.items(), key = lambda item: item[1]['created_at'])

which outputs:

[
    ('1366451044687880192', {'created_at': 'Mon Mar 01 18:11:31 +0000 2021', 'id': 1366463640451233323}),
    ('1366463640451256323', {'created_at': 'Mon Mar 05 19:01:34 +0000 2021', 'id': 1366463640451256323})
]

Upvotes: 1

Related Questions