簡體   English   中英

獲取嵌套字典中的最新日期

[英]Get the most recent date in a nested dictionary

我正在嘗試獲取嵌套詞典中的最新日期。 日期是字符串,可以在關鍵字forth下的數量不定的字典中找到。 這是我的方法:

data = {
    "first": {
        "second": {
            "third_1": {"forth": "2022-01-01"},
            "third_2": {"forth": None},
            "third_3": {"forth": "2021-01-01"},
        }
    }
}


def get_max(data, key):
    tmp = []
    for item in data.values():
        tmp.append(item.get(key))
    tmp = [
        datetime.strptime(date, "%Y-%m-%d").date().strftime("%Y-%m-%d")
        for date in tmp
        if date
    ]

    return max(tmp)


out = data["first"]["second"]
out = get_max(data=out, key="forth")
out

有什么我可以改進的嗎?

我認為比較日期而不將它們轉換為 object 也可以

您也可以使用以下方法

data = {
    "first": {
        "second": {
            "third_1": {"forth": "2022-01-01"},
            "third_2": {"forth": None},
            "third_3": {"forth": "2021-01-01"},
        }
    }
}
max(filter(lambda x: x["forth"], data["first"]["second"].values()), key=lambda x: x["forth"])

嘗試:

Max = max(d for a,b in data["first"]["second"].items() for c,d in b.items() if d != None)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM