python比较时间先后顺序,在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

解决方案

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.

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.

你可能感兴趣的:(python比较时间先后顺序)