Order/Sort a dictionary of dictionaries by a value of the sub-dictionary

Viewed 35

I have a dictionary where the values are dictionaries too. I want to order the key/values of the main dictionary by a value of the value-dictionaries (in the example by date).

Example:

a = {
    1: {'Text': 'Test1', 'Date': '2021-05-11'},
    2: {'Text': 'Test2', 'Date': '2021-12-12'},
    3: {'Text': 'Test3', 'Date': '2021-01-01'}
    }

The ordered object should look like this:

a = {
    3: {'Text': 'Test3', 'Date': '2021-01-01'},
    1: {'Text': 'Test1', 'Date': '2021-05-11'},
    2: {'Text': 'Test2', 'Date': '2021-12-12'}
    }

I managed to do this with a list of dictionaries:

a = [
    {'ID': 1, 'Text': 'Test1', 'Date': '2021-05-11'},
    {'ID': 2, 'Text': 'Test2', 'Date': '2021-12-12'},
    {'ID': 3, 'Text': 'Test3', 'Date': '2021-01-01'},
    ]

a = sorted(a, key=lambda k: k['Date'])

But I cannot figure it out with a dictionary of dictionaries. Maybe someone can point me in the right direction.

Thanks in advance. Frank

1 Answers

You need to use a.items() and then use the key as key=lambda x:x[1]['Date']. Second element of x is the value.

>>> a
{1: {'Text': 'Test1', 'Date': '2021-05-11'}, 2: {'Text': 'Test2', 'Date': '2021-12-12'}, 3: {'Text': 'Test3', 'Date': '2021-01-01'}}
>>> dict(sorted(a.items(), key=lambda x:x[1]['Date']))
{3: {'Text': 'Test3', 'Date': '2021-01-01'}, 1: {'Text': 'Test1', 'Date': '2021-05-11'}, 2: {'Text': 'Test2', 'Date': '2021-12-12'}}
Related