Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort python dictionary by date key

In the main dictionary, the date was a value. There were data with same date. So then I took the date and grouped it by creating a 2 dimensional dict where date is the key.

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

Now I want to sort it by the date descending so that it will look like this:

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

How can I achieve that?
I am using python 2.6

like image 236
Imrul.H Avatar asked Dec 07 '15 08:12

Imrul.H


2 Answers

The idea here is to use OrderedDict as dictionary has no scope for ordering while OrderedDict preserves the entry order.

The idea here is to use list of tuples of (key, value) pairs as dictionary has no scope for ordering while OrderedDict preserves the entry order. Also we must convert the keys to actual datetime object for the sort to work perfectly otherwise sorting on string based fields happen alphabetically.

Code :

from datetime import datetime
#from collections import OrderedDict


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

#ordered_data = OrderedDict(
#    sorted(data.items(), key = lambda x:datetime.strptime(x[0], '%d-%m-%Y'), reverse=True))

#Since OP is using python 2.6 where OrderedDict is not present, I changed the solution and the original solution is commented out
ordered_data = sorted(data.items(), key = lambda x:datetime.strptime(x[0], '%d-%m-%Y'), reverse=True)

print(ordered_data)

Output :

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

Explanation : (For converting keys to datetime for sorting)

If you keep the date field as string then the lexicographical order is considered and 3 comes after 0 hence a>b is True but same is not true for their date counterparts. Feb definitely comes after Jan.

a = "30-01-2015"
b = "01-02-2015"

print(a>b)    #True

a_datetime = datetime.strptime(a, '%d-%m-%Y')
b_datetime = datetime.strptime(b, '%d-%m-%Y')

print(a_datetime>b_datetime) #False
like image 185
Shivendra Avatar answered Oct 10 '22 13:10

Shivendra


You can use the sorted method of python that will automatically sort your data on date and return a list.

data = {"01-01-2015" : "some data","05-05-2015" : "some data","03-04-2015" : "some data"}
sorted(data.items(), reverse=True)

that will produce the result:

[('05-05-2015', 'some data'), ('03-04-2015', 'some data'), ('01-01-2015', 'some data')]
like image 42
Aalok kumar Avatar answered Oct 10 '22 14:10

Aalok kumar