【发布时间】:2021-07-12 11:56:29
【问题描述】:
我正在尝试按日期时间对以下嵌套字典进行排序,以便首先获得最新记录:
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"],
},
}
首先我尝试做一个简单的排序:
sorted_result_devices = sorted(result_devices, reverse=True)
但它只返回日期时间,而不是完整的嵌套字典:
sorted_result_devices=
[
datetime.datetime(2021, 7, 11, 14, 17, 3),
datetime.datetime(2021, 7, 8, 14, 22, 23),
]
然后我尝试使用 lambda 函数:
sorted_result_devices =sorted(result_devices, reverse=True, key= lambda x:x[0])
但它返回了一个 TypeError: TypeError: 'datetime.datetime' object is not subscriptable
¿对像这样的嵌套字典进行排序的正确方法是什么?
提前致谢
【问题讨论】:
标签: python python-3.x sorting dictionary python-datetime