简体   繁体   中英

Improve code readability of a Python lambda expression with condition

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 by dict() in this example.

OrderedDict(
    sorted(file_dict.items(),
           key=lambda t: re.findall(r"\d{8}", t[0]),
           reverse=True))

# OR
dict(
    sorted(file_dict.items(),
           key=lambda t: re.findall(r"\d{8}", t[0]),
           reverse=True))

Results:

OrderedDict([('scdfws_20221104eaf2we', 5),
             ('asda_20221003:ada', 1),
             ('iasndcfiopsadn', 9)])

# OR
{'scdfws_20221104eaf2we': 5, 'asda_20221003:ada': 1, 'iasndcfiopsadn': 9}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM