Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort python dictionary by Keys formatted as strings

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.

like image 288
zpesk Avatar asked Mar 13 '26 12:03

zpesk


2 Answers

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.

like image 184
mgilson Avatar answered Mar 16 '26 01:03

mgilson


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
like image 20
eumiro Avatar answered Mar 16 '26 02:03

eumiro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!