简体   繁体   English

按日期键排序python字典

[英]Sort python dictionary by date keys

I have a dictinary like below and trying to sort that by keys(which are date time object): 我有一个像下面的dictinary并尝试按键(这是日期时间对象)排序:

def t(date_st):
    return datetime.strptime(date_st, '%d-%m-%Y')

def sort_dict_data(data):
keylist = data.keys()
keylist.sort()
sorted_x = {}
for key in keylist:
    sorted_x.update({datetime.strftime(key, '%d-%m-%Y'):data.get(key)})
return sorted_x



print sort_dict_data({t('07-07-2012'): 3.5, t('09-07-2012'): 9.0, t('08-07-2012'): 5.0})
results: {'07-07-2012': 3.5, '09-07-2012': 9.0, '08-07-2012': 5.0}

How I can get that like: 我怎么能这样:

{'07-07-2012': 3.5, '08-07-2012': 5.0, '09-07-2012': 9.0}

Thanks in advance. 提前致谢。

Dicts don't have a reliable order. Dicts没有可靠的订单。

You can use an OrderedDict instead. 您可以使用OrderedDict

def sort_dict_data(data):
    return OrderedDict((datetime.strftime(k, '%d-%m-%Y'), v)
                       for k, v in sorted(data.iteritems()))

See it working online: ideone 看到它在线工作: ideone

Note that the OrderedDict orders according to insertion order, not by key order. 请注意, OrderedDict根据插入顺序而不是按键顺序进行排序。 The above code inserts items into the OrderedDict in key order, giving you the result you want. 上面的代码按顺序将项目插入OrderedDict ,为您提供所需的结果。 But it is important to remember that any later additions you make to the dictionary will appear at the end, not in the correct position according to key order. 但重要的是要记住,您对字典的任何后续添加都将出现在最后,而不是根据键顺序在正确的位置。

OrderedDict preserves order of insertion (the chronology), not key order. OrderedDict保留插入顺序(年表),而不是键顺序。 Plain dict's don't preserve either. 普通字典也不保留。

For dictionaries sorted by keys, you likely want a Treap, Red-Black tree, or one of the many other tree datastructures known to computer science. 对于按键排序的字典,您可能需要Treap,Red-Black树或计算机科学已知的许多其他树数据结构之一。

Treaps are fast on average, but will be a bit slow once in an infrequent while, as it rebalances itself. Treaps的平均速度很快,但在不经常的时候会有点慢,因为它会重新平衡。

Red-Black trees are well known, relatively complex (compared to treaps), and give OK performance on average. 红黑树是众所周知的,相对复杂(与treaps相比),并且平均表现良好。 Their chief benefit is that they don't have highly variable performance, making them sometimes-nice in user interfaces. 他们的主要好处是他们没有高度可变的性能,使他们有时在用户界面上很好。

I recently did a performance comparison of datastructures that are like dicts but with sorted keys. 我最近对数据结构进行了性能比较,这些数据结构类似于dicts但是带有排序键。 It can be found here: http://stromberg.dnsalias.org/~strombrg/python-tree-and-heap-comparison/ 它可以在这里找到: http//stromberg.dnsalias.org/~strombrg/python-tree-and-heap-comparison/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM