Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a dictionary (with date keys) in Python

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

like image 389
skyeagle Avatar asked Oct 20 '10 11:10

skyeagle


People also ask

Can we sort dictionary with keys in Python?

Python offers the built-in keys functions keys() and values() functions to sort the dictionary. It takes any iterable as an argument and returns the sorted list of keys. We can use the keys to sort the dictionary in the ascending order.

How do I sort by date in Python?

To sort a Python date string list using the sort function, you'll have to convert the dates in objects and apply the sort on them. For this you can use the key named attribute of the sort function and provide it a lambda that creates a datetime object for each date and compares them based on this date object.

How do you sort data in a dictionary Python?

To sort a dictionary by value in Python you can use the sorted() function. Python's sorted() function can be used to sort dictionaries by key, which allows for a custom sorting method. sorted() takes three arguments: object, key, and reverse. Dictionaries are unordered data structures.


4 Answers

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.

like image 188
Dave Webb Avatar answered Oct 02 '22 12:10

Dave Webb


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

like image 22
Ignacio Vazquez-Abrams Avatar answered Oct 03 '22 12:10

Ignacio Vazquez-Abrams


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
like image 45
Jungle Hunter Avatar answered Oct 04 '22 12:10

Jungle Hunter


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})]
like image 24
SilentGhost Avatar answered Oct 02 '22 12:10

SilentGhost