3

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

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

4

2 回答 2

9
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)])
于 2011-07-13T11:21:37.883 回答
5

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

# 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 的答案以获得更好的示例。Usingoperator.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)
于 2011-07-13T11:16:53.777 回答