0

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

4
  • 8
    define a regular function? Commented Oct 3, 2022 at 12:14
  • Do the keys already sort correctly as strings? Commented Oct 3, 2022 at 12:27
  • len(re.findall("\d{8}",t[0]) as x) could be accomplished with an assignment expression len(x := re.findall("\d{8}",t[0])). I'm not sure it's more readable, but there it is. Commented Oct 3, 2022 at 13:13
  • 1
    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. Commented Oct 3, 2022 at 13:28

1 Answer 1

1

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}
Sign up to request clarification or add additional context in comments.

2 Comments

Python 3's dicts are insertion ordered by default as @Steven Rumbalski wrote
Yes, but @david.t_92 uses an OrderedDict, so I keep his choice. I don't know what he wants to do with this data afterwards that's why... Answer edited btw

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.