27

I have a dictionary. The keys are dates (datetime). I need to sort the dictionary so that the values in the dictionary are sorted by date - so that by iterating through the dictionary, I am processing items in the desired chronological (i.e. date/time) order.

How may I sort such a dictionary by date?

Example:

mydict = { '2000-01-01': {fld_1: 1, fld_2: 42}, '2000-01-02': {fld_1:23, fld_2: 22.17} }

Note: I am using strings here instead of datetime, to keep the example simple

2
  • 2
    sorting should work in yyyy-mm-dd format as strings also. Commented Oct 20, 2010 at 11:49
  • Glad someone already asked this ;) Commented Jun 21, 2011 at 9:34

6 Answers 6

22

If you're using Python 2.7+ or 3.1+ you could create an OrderedDict from collections from a sort of your dictionary and then iterate through that.

from collections import OrderedDict

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

However, depending on what you want to do it's probably easier to iterate over a sorted list of keys from your dict.

Sign up to request clarification or add additional context in comments.

4 Comments

What might be even better than creating an OrderedDict or retrieving and then sorting the keys after any changes are made to the dictionary, would be a SortedDict.
Why do people persist in using key when they just want the natural sort order?
For Python newbies like me, @martineau meant that you can accomplish the same goal like this ordered = OrderedDict(sorted(mydict.items()) Note that the sort works the same if the keys are actual datetime objects and not strings
@jbustamovej: I literally meant download, install, and use the sorteddict extension module instead of what's in this answer (or the alternative in your comment). "The main benefit of sorteddicts is that you never have to explicitly sort."
6

Dictionaries are unsortable. Iterate over sorted(mydict.keys()) instead.

1 Comment

it is possible also say sorted(mydict) if you prefer.
5

Dictionaries never store anything in some order. But you can get a list of keys using d.keys() which could be sorted. Iterate over a generator like below.

def sortdict(d):
    for key in sorted(d): yield d[key]

Using this you will be able to iterate over values in chronological order.

for value in sortdict(mydict):
    # your code
    pass

2 Comments

you don't need .keys() there
@SilentGhost: oh yeah! there you go.
2

since your date strings seem to be in a proper format you could just do:

>>> sorted(mydict.items())         # iteritems in py2k
[('2000-01-01', {'fld_2': 42, 'fld_1': 1}), ('2000-01-02', {'fld_2': 22.17, 'fld_1': 23})]

Comments

0

I'm sure that python knows how to compare dates. So:

def sortedDictValues(adict):
 items = adict.items()
 items.sort()
 return [value for key, value in items]

2 Comments

Python compares datetime objects without any problems. In this case YYYY-MM-DD strings are also correctly comparable. A problem would be date in format MM/DD/YYYY or DD.MM.YYYY, but not with YYYY-MM-DD.
The last three lines of your code can be also written as return [value for key, value in sorted(adict.items())]
0

Python 2.7 (released on July 3rd, 2010) supports an ordered dictionary type:

http://www.python.org/download/releases/2.7/

3 Comments

ordered dictionary remembers the order of insertion. But blist module has sorteddict pypi.python.org/pypi/blist
but doesn't the order dictionary also have a "sort" function?
If you put it that way, yes. And then it would stay for future use. More natural for me would be to sorteddict.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.