【问题标题】:Python dictionary TypeError in nested dictionaries using datetime as a key使用日期时间作为键的嵌套字典中的 Python 字典 TypeError
【发布时间】: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


    【解决方案1】:

    使用result_devices.items() 作为sorted 中的args

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

    输出

    [(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']})]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-27
      • 2010-12-08
      • 2017-03-09
      • 2016-11-14
      • 1970-01-01
      • 2014-03-30
      • 2021-02-09
      • 2021-05-10
      相关资源
      最近更新 更多