I have a dictionary with strings as keys formatted as yyyy-mm-dd and want to sort the dictionary by keys with the earliest dates first:
I am currently using sorted(datesAndText.keys()) but this isn’t reliably working because the month and day fields are not always zero padded.
I have looked at Sort python dictionary by date keys and How do I sort this list in Python, if my date is in a String? but I can’t seem to adopt them to by specific case.
Are you sure your keys are exactly in the format
yyyy-mm-dd? For example:You may be forced to sort something like this:
Another solution (assuming your years are all 4 digits):
I’m not sure which would be faster. I suppose it’s a candidate for
timeit.