按日期键排序python字典 [英] Sort python dictionary by date keys

查看:277
本文介绍了按日期键排序python字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的常规,并试图通过键(这是日期时间对象)排序:

I have a dictinary like below and trying to sort that by keys(which are date time object):

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}

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

提前感谢

推荐答案

Dicts没有可靠的订单。

Dicts don't have a reliable order.

您可以使用 OrderedDict

You can use an OrderedDict instead.

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

看到它在线工作: ideone

请注意, OrderedDict 根据插入订单,而不是按顺序。上述代码按照顺序将项目插入 OrderedDict 中,为您提供所需的结果。但重要的是要记住,您对字典的任何后续添加将会显示在结尾,而不是根据关键顺序处于正确的位置。

Note that the OrderedDict orders according to insertion order, not by key order. The above code inserts items into the OrderedDict in key order, giving you the result you want. 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.

这篇关于按日期键排序python字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆