Richard Knop
Richard Knop

Reputation: 83697

Sort huge dictionary of dictionaries by nested value efficiently?

How can I sort a dictionary like this (simplified version):

x = {
    '1': {
        'type': 'a',
        'created_at': 'date time object here',
    },
    '2': {
        'type': 'b',
        'created_at': 'date time object here',
    },
    '3': {
        'type': 'a',
        'created_at': 'date time object here',
    },
}

I have a dictionary with structure like above with several hundred thousands keys, I need to sort it by created_at value, which is a date time object.

Upvotes: 0

Views: 80

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121484

With a simple key function:

sorted(d.iteritems(), key=lambda i: i[1]['created_at'])

This produces a sorted list of (key, nested_dict) tuples, sorted on the 'created_at' key of the nested dictionaries.

In Python 3, replace iteritems() with items(). You cannot avoid creating a list; sorting requires an orderable, mutable sequence to move the items around in.

Upvotes: 3

Related Questions