Python OrderedDict按日期排序



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

谁有什么建议,如何做到这一点?

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)])

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)

相关内容

  • 没有找到相关文章

最新更新