简体   繁体   English

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

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

I have below list:我有以下清单:

[
    {
        "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"
    }
]
    

Above data is a list of dict .以上数据是dictlist Each dict has a list of attributes .每个dict都有一个attributes list attriutes is again a dict which has many items and Event Date . attriutes又是一个字典,它有很多项目和Event Date I have to sort all the dicts inside list based on ascending order of Event Date .我必须根据Event Date升序对列表中的所有字典进行排序。 How can we achieve this?我们怎样才能做到这一点?

You need to get the datetime string firstly, then format the datetime string:您需要先获取日期时间字符串,然后格式化日期时间字符串:

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"))

Or more readable way:或更易读的方式:

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)

And gave me:并给了我:

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

You want to sort by key.您想按键排序。

This is how you would do it for a simpler example:对于更简单的示例,您将如何执行此操作:

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"])

For your specific case, since it is more complicated, I would create a function instead of using a lambda expression.对于您的特定情况,由于它更复杂,我将创建一个函数而不是使用 lambda 表达式。 Additionally, I will use datetime to help me compare the date strings.此外,我将使用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