sort python dictionary by date 1

sort python dictionary by date

from datetime import datetime
from collections import OrderedDict # For python 2.7 and above

data = { "01-01-2015" : "some data",
    	 "05-05-2015" : "some data",
         "03-04-2015" : "some data" }

# For python 2.7 and above:
ordered_data = OrderedDict(
    sorted(data.items(), key = lambda x:datetime.strptime(x[0], '%d-%m-%Y')) )

# For python 2.6 and below where OrderedDict is not present:
# ordered_data = sorted(data.items(), key = lambda x:datetime.strptime(x[0], '%d-%m-%Y'))


#Output :
[('01-01-2015', 'some data'), 
 ('03-04-2015', 'some data'), 
 ('05-05-2015', 'some data')]

Here is what the above code is Doing:
1. We are sorting the dictionary by the key, which is a date string.
2. We are using the datetime.strptime() function to convert the date string to a datetime object.
3. We are using the lambda function to pass the key to the datetime.strptime() function.
4. We are using the sorted() function to sort the dictionary by the key.
5. We are using the OrderedDict() function to convert the sorted list to a dictionary.

Similar Posts