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:
>>> '2010-1-15' < '2010-02-15'
False
You may be forced to sort something like this:
sorted(d,key=lambda x: [int(y) for y in x.split('-')])
Another solution (assuming your years are all 4 digits):
sorted(d,key=lambda x: [y.zfill(2) for y in x.split('-')])
I'm not sure which would be faster. I suppose it's a candidate for timeit.
Dates in yyyy-mm-dd format sort the same way both alphabetically and chronologically, so you can use standard sorted:
for k, v in sorted(datesAndText.items()):
# do something with key and value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With