簡體   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