繁体   English   中英

如何根据 Python 中的日期时间对字典列表进行排序

[英]How to sort a list of dict based on their datetime in Python

我有以下清单:

[
    {
        "attributes": 
        [
            {
                "label": "Event Date",
                "value": "Tue, 29 Jun 2021 18:30:00 GMT"
            }
        ],
        "event": "DT2"
    },
    {
        "attributes": 
        [
            {
                "label": "DT3",
                "value": true
            },
            {
                "label": "Event Date",
                "value": "Thu, 22 Jul 2021 18:30:00 GMT"
            }
        ],
        "event": "DT5"
    },
    {
        "attributes": [
            {
                "label": "DT6",
                "value": 1.0
            },
            {
                "label": "Event Date",
                "value": "Thu, 08 Jul 2021 18:30:00 GMT"
            }
        ],
        "event": "DT7"
    }
]
    

以上数据是dictlist 每个dict都有一个attributes list attriutes又是一个字典,它有很多项目和Event Date 我必须根据Event Date升序对列表中的所有字典进行排序。 我们怎样才能做到这一点?

您需要先获取日期时间字符串,然后格式化日期时间字符串:

import datetime

lst = [
    {
        "attributes": 
        [
            {
                "label": "Event Date",
                "value": "Tue, 29 Jun 2021 18:30:00 GMT"
            }
        ],
        "event": "DT2"
    },
    {
        "attributes": 
        [
            {
                "label": "DT3",
                "value": True
            },
            {
                "label": "Event Date",
                "value": "Thu, 22 Jul 2021 18:30:00 GMT"
            }
        ],
        "event": "DT5"
    },
    {
        "attributes": [
            {
                "label": "DT6",
                "value": 1.0
            },
            {
                "label": "Event Date",
                "value": "Thu, 08 Jul 2021 18:30:00 GMT"
            }
        ],
        "event": "DT7"
    }
]
    
lst.sort(key=lambda x: datetime.datetime.strptime(next(attr["value"] for attr in x["attributes"] if attr["label"] == "Event Date"), "%a, %d %b %Y %X %Z"))

或更易读的方式:

def check(x):
    for attr in x["attributes"]:
        if attr["label"] == "Event Date":
            return datetime.datetime.strptime(attr["value"], "%a, %d %b %Y %X %Z")
 
lst.sort(key=check)

并给了我:

[{'attributes': [{'label': 'Event Date',
    'value': 'Tue, 29 Jun 2021 18:30:00 GMT'}],
  'event': 'DT2'},
 {'attributes': [{'label': 'DT6', 'value': 1.0},
   {'label': 'Event Date', 'value': 'Thu, 08 Jul 2021 18:30:00 GMT'}],
  'event': 'DT7'},
 {'attributes': [{'label': 'DT3', 'value': True},
   {'label': 'Event Date', 'value': 'Thu, 22 Jul 2021 18:30:00 GMT'}],
  'event': 'DT5'}]

您想按键排序。

对于更简单的示例,您将如何执行此操作:

my_list = [
    {
        "foo": 5,
        "bar": 4,
    },
    {
        "foo": 3,
        "bar": 2,
    },
    {
        "foo": 1,
        "bar": 0,
    },
]

# This will sort the list according to the "foo" in each dictionary.
my_list.sort(key=lambda dictionary: dictionary["foo"])

对于您的特定情况,由于它更复杂,我将创建一个函数而不是使用 lambda 表达式。 此外,我将使用datetime来帮助我比较日期字符串。

from datetime import datetime

def key_function(dictionary):
    attributes = dictionary["attributes"]
    for attribute in attributes:
        if attribute["label"] == "Event Date":
            date_string = attribute["value"]
            date = datetime.strptime(date_string, "%a, %d %b %Y %X %Z")
            # Compare dates according to their POSIX timestamp
            # I am assuming the dates will be after 1970
            return date.timestamp()
    raise ValueError("Event Date attribute wasn't found")

my_list.sort(key=key_function)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM