Home > Software design >  Get the most recent date in a nested dictionary
Get the most recent date in a nested dictionary

Time:10-19

I am trying to get the most recent date in a nested dicionary. The dates are strings and can be found in a variable number of dictionaries under the key forth. This is my approach:

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

Is there anything I can improve?

CodePudding user response:

try:

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

CodePudding user response:

I think comparing dates without converting them into object will also work

You can use below approach as well

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