按嵌套值对大型词典进行有效排序?

2024-06-25 23:22:24 发布

您现在位置:Python中文网/ 问答频道 /正文

如何对这样的词典进行排序(简化版):

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',
    },
}

我有一个字典,上面的结构有几十万个键,我需要按创建的值对它进行排序,这是一个日期时间对象。你知道吗


Tags: 对象date字典hereobjecttime排序type
1条回答
网友
1楼 · 发布于 2024-06-25 23:22:24

使用一个简单的key函数:

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

这将生成一个(key, nested_dict)元组的排序列表,按嵌套字典的'created_at'键排序。你知道吗

在python3中,将iteritems()替换为items()。你不能避免创建一个列表;排序需要一个有序的、可变的序列来移动项目。你知道吗

相关问题 更多 >