First of all I do not know if these types of questions are appropriate in stackoverflow.
I have the following dict:
file_dict = {"asda_20221003:ada":1, "scdfws_20221104eaf2we":5, "iasndcfiopsadn":9}
The key values of the dict always contains a date with the format %Y%m%d, what i want i to obtain the value for the key that have the highest date.
What I have done is the following:
OrderedDict(sorted(file_dict.items(), key=lambda t: datetime.strptime(re.findall("\d{8}",t[0])[0], "%Y%m%d") if len(re.findall("\d{8}",t[0])) > 0 else datetime.min, reverse=True))
This expression works but it is unreadable. Is there any way in order to improve it?
what i would like is to asigne at some point re.findall("\d{8}",t[0]) to a variable (for example date) and use this one for all the expression.
Something like this:
OrderedDict(sorted(file_dict.items(), key=lambda t: datetime.strptime(x[0], "%Y%m%d") if len(re.findall("\d{8}",t[0]) as x) > 0 else None, reverse=True))
I am also open for other ways to perform this operation
You can simply compare list of strings and not compare datetimes.
As @Steven Rumbalski said: Note that as of Python 3.7 dictionaries are guaranteed to retain the insertion order of the keys, so
OrderedDict()can be replaced bydict()in this example.Results: