在Python中排序字典(带日期键) [英] Sorting a dictionary (with date keys) in Python

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

问题描述

我有一本字典。键是日期(datetime)。我需要对字典进行排序,以便字典中的值按日期排序 - 因此,通过遍历字典,我正按期望的时间顺序(即日期/时间)顺序处理项目。



如何按日期排序这样的字典?



示例:

  mydict = {'2000-01-01':{fld_1:1,fld_2:42},'2000-01-02':{fld_1:23,fld_2:22.17}} 

注意:我正在使用字符串而不是datetime,以保持示例简单

解决方案

如果您使用Python 2.7+或3.1+,您可以创建一个集合 中的.html#collections.OrderedDictrel =noreferrer> OrderedDict 你的字典然后重复一遍。

  ordered = OrderedDict(sorted(mydict.items(),key = lambda t:t [0]))

然而,dep结束于你想做的事情,可能更容易从你的dict迭代一个有序的密钥列表。


I have a dictionary. The keys are dates (datetime). I need to sort the dictionary so that the values in the dictionary are sorted by date - so that by iterating through the dictionary, I am processing items in the desired chronological (i.e. date/time) order.

How may I sort such a dictionary by date?

Example:

mydict = { '2000-01-01': {fld_1: 1, fld_2: 42}, '2000-01-02': {fld_1:23, fld_2: 22.17} }

Note: I am using strings here instead of datetime, to keep the example simple

解决方案

If you're using Python 2.7+ or 3.1+ you could create an OrderedDict from collections from a sort of your dictionary and then iterate through that.

ordered = OrderedDict(sorted(mydict.items(), key=lambda t: t[0]))

However, depending on what you want to do it's probably easier to iterate over a sorted list of keys from your dict.

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

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