在Python中排序字典(带日期键) [英] Sorting a dictionary (with date keys) in Python
问题描述
如何按日期排序这样的字典?
示例:
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屋!