按日期排序的Python OrderedDict

时间:2011-07-13 11:04:10

标签: python datetime date ordereddictionary

我正在尝试使用OrderedDict(Raymond Hettingers version用于pre2.7 Python),其中我的键是日期。但是它没有正确排序,我想它可能是根据ID订购。

有没有人对如何做到这一点有任何建议?

2 个答案:

答案 0 :(得分:8)

In [1]: from collections import OrderedDict

In [2]: import operator

In [3]: from datetime import date

In [4]: d = {date(2012, 1, 1): 123, date(2010,2,5): 542, date(2011,3,3):76 }

In [5]: d # Good old dict
Out[5]: #it seems sorted, but it isn't guaranteed to be that way.
{datetime.date(2010, 2, 5): 542,
 datetime.date(2011, 3, 3): 76,
 datetime.date(2012, 1, 1): 123}

In [6]: o = OrderedDict(sorted(d.items(), key=operator.itemgetter(0)))

In [7]: o #Now it is ordered(and sorted, because we give it by sorted order.).
Out[7]: OrderedDict([(datetime.date(2010, 2, 5), 542), (datetime.date(2011, 3, 3), 76), (datetime.date(2012, 1, 1), 123)])

答案 1 :(得分:5)

OrderedDict,根据其docstring,是一种记住插入顺序的字典。 因此,您需要以正确的顺序手动插入键/值对。

# assuming unordered_dict is a dict that contains your data 
ordered_dict = OrderedDict()
for key, value in sorted(unordered_dict.iteritems(), key=lambda t: t[0]):
    ordered_dict[key] = value

编辑:有关更好的例子,请参阅utdemir的答案。使用operator.itemgetter可以提供更好的性能(速度提高60%,我使用下面的基准代码),这是一种更好的编码风格。您可以将OrderedDict直接应用于sorted(...)

a = (1, 2)

empty__func = 0
def empty():
    for i in xrange(N_RUNS):
        empty__func

lambda_func = lambda t: t[0]
def using_lambda():
    for i in xrange(N_RUNS):
        lambda_func(a)

getter_func = itemgetter(0)
def using_getter():
    for i in xrange(N_RUNS):
        getter_func(a)