sort python dictionary by date

Solutions on MaxInterview for sort python dictionary by date by the best coders in the world

showing results for - "sort python dictionary by date"
Eireann
27 Apr 2019
1from datetime import datetime
2from collections import OrderedDict # For python 2.7 and above
3
4data = { "01-01-2015" : "some data",
5    	 "05-05-2015" : "some data",
6         "03-04-2015" : "some data" }
7
8# For python 2.7 and above:
9ordered_data = OrderedDict(
10    sorted(data.items(), key = lambda x:datetime.strptime(x[0], '%d-%m-%Y')) )
11
12# For python 2.6 and below where OrderedDict is not present:
13# ordered_data = sorted(data.items(), key = lambda x:datetime.strptime(x[0], '%d-%m-%Y'))
14
15print(ordered_data)
16
17#Output :
18[('01-01-2015', 'some data'), 
19 ('03-04-2015', 'some data'), 
20 ('05-05-2015', 'some data')]