Janith Chinthana
Janith Chinthana

Reputation: 3844

Sort a dict with date key in Python

I have a dict with date time key as bellow

{u'2014-04-21 14:46': {u'status': 0, u'created': u'21-04-2014 14:46', u'duration': u'0:12'}, u'2014-04-22 10:31': {u'status': 0, u'created': u'22-04-2014 10:31', u'duration': u'1:28}}

I need to sort that with date time key.

I have already tried as below which is mention in this question and it is not sorting as expected.

ordered = OrderedDict(sorted(mydict.items(), key=lambda t: t[0]))

In that question key is 2014-04-21 and mine is 2014-04-21 14:46.

Any help would appreciate.

Upvotes: 1

Views: 1136

Answers (1)

Krumelur
Krumelur

Reputation: 32497

As far as I can see from your sample set, you are using ISO dates.

ISO dates are alphabetically sortable. There is no need to handle the special case of them being dates. I see nothing wrong with your code.

Running your code, e.g.

>>> list(OrderedDict(sorted(mydict.items(), key=lambda t: t[0])))

produces the keys sorted, e.g.

[u'2014-04-21 14:46', u'2014-04-22 10:31']

To sort the list in decending order, use

>>> list(OrderedDict(sorted(mydict.items(), key=lambda t: t[0], reversed=True)))

Upvotes: 1

Related Questions