Python dictionary TypeError in nested dictionaries using datetime as a key

Viewed 52

I'm trying to sort the following nested dictionary by datetime in order to have the newest records first:

result_devices= 
{
    datetime.datetime(2021, 7, 8, 14, 22, 23): {
        0: ["VC", "10.192.41.15", "-", "OK"],
        1: ["tef", "2.113.85.155", "-", "OK"],
        2: ["AP", "192.168.192.181", "24:f2:7f:ce:f2:ca", "OK"],
        3: ["AP", "192.168.192.182", "-", "OK"],
        4: ["AP", "192.168.192.184", "24:f2:7f:cf:74:14", "OK"],
        5: ["AP", "192.168.192.185", "24:f2:7f:cf:73:74", "OK"],        
    },
    datetime.datetime(2021, 7, 11, 14, 17, 3): {
        6: ["VC", "10.192.41.15", "-", "OK"],
        7: ["tef", "2.113.85.155", "-", "OK"],
        8: ["AP", "192.168.192.181", "24:f2:7f:ce:f2:ca", "OK"],
        9: ["AP", "192.168.192.182", "-", "OK"],
        10: ["AP", "192.168.192.184", "24:f2:7f:cf:74:14", "OK"],        
    },
}

First I tried to make a simple sort:

sorted_result_devices = sorted(result_devices, reverse=True)

But it only returned the datetimes, not the full nested dictionary:

sorted_result_devices=
[
    datetime.datetime(2021, 7, 11, 14, 17, 3),
    datetime.datetime(2021, 7, 8, 14, 22, 23),
]

Then I tried to use the lambda function:

sorted_result_devices =sorted(result_devices, reverse=True, key= lambda x:x[0])

But it returned a TypeError: TypeError: 'datetime.datetime' object is not subscriptable

¿Which is the proper way to sort a nested dictionary like this one?

Thanks in advance

1 Answers

Use result_devices.items() as the args in sorted

sorted_result_devices = sorted(result_devices.items(), reverse=True)

Output

[(datetime.datetime(2021, 7, 11, 14, 17, 3),
  {6: ['VC', '10.192.41.15', '-', 'OK'],
   7: ['tef', '2.113.85.155', '-', 'OK'],
   8: ['AP', '192.168.192.181', '24:f2:7f:ce:f2:ca', 'OK'],
   9: ['AP', '192.168.192.182', '-', 'OK'],
   10: ['AP', '192.168.192.184', '24:f2:7f:cf:74:14', 'OK']}),
 (datetime.datetime(2021, 7, 8, 14, 22, 23),
  {0: ['VC', '10.192.41.15', '-', 'OK'],
   1: ['tef', '2.113.85.155', '-', 'OK'],
   2: ['AP', '192.168.192.181', '24:f2:7f:ce:f2:ca', 'OK'],
   3: ['AP', '192.168.192.182', '-', 'OK'],
   4: ['AP', '192.168.192.184', '24:f2:7f:cf:74:14', 'OK'],
   5: ['AP', '192.168.192.185', '24:f2:7f:cf:73:74', 'OK']})]
Related