Python OrderedDict ordered by date

2019-07-04 05:02发布

I am trying to use an OrderedDict (Raymond Hettingers version for pre2.7 Python) where my keys are dates. However it does not order them correctly, I imagine it may be ordering based on the ID.

Does anyone have any suggestions of how this could be done?

2条回答
爷、活的狠高调
2楼-- · 2019-07-04 05:34
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)])
查看更多
Viruses.
3楼-- · 2019-07-04 05:39

OrderedDict, according to its docstring, is a kind of dict that remembers insertion order. Thus, you need to manually insert the key/value pairs in the correct order.

# 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

edit: See utdemir's answer for a better example. Using operator.itemgetter gives you better performance (60% faster, I use the benchmark code below) and it's a better coding style. And you can apply OrderedDict directly to 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)
查看更多
登录 后发表回答