在 Python 中对字典(带有日期键)进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3977310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sorting a dictionary (with date keys) in Python
提问by skyeagle
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
注意:我在这里使用字符串而不是日期时间,以保持示例简单
回答by Ignacio Vazquez-Abrams
Dictionaries are unsortable. Iterate over sorted(mydict.keys())instead.
字典是无法分类的。sorted(mydict.keys())而是迭代。
回答by foret
I'm sure that python knows how to compare dates. So:
我确信 python 知道如何比较日期。所以:
def sortedDictValues(adict):
items = adict.items()
items.sort()
return [value for key, value in items]
回答by SilentGhost
since your date strings seem to be in a proper format you could just do:
由于您的日期字符串似乎采用正确的格式,您可以这样做:
>>> sorted(mydict.items()) # iteritems in py2k
[('2000-01-01', {'fld_2': 42, 'fld_1': 1}), ('2000-01-02', {'fld_2': 22.17, 'fld_1': 23})]
回答by Jungle Hunter
Dictionaries never store anything in some order. But you can get a list of keys using d.keys()which could be sorted. Iterate over a generator like below.
字典从不以某种顺序存储任何东西。但是您可以获得d.keys()可以排序的键列表。迭代如下所示的生成器。
def sortdict(d):
for key in sorted(d): yield d[key]
Using this you will be able to iterate over values in chronological order.
使用它,您将能够按时间顺序迭代值。
for value in sortdict(mydict):
# your code
pass
回答by Dave Webb
If you're using Python 2.7+ or 3.1+ you could create an OrderedDictfrom collectionsfrom a sort of your dictionary and then iterate through that.
如果您使用的是 Python 2.7+ 或 3.1+,您可以从某种字典中创建一个OrderedDictfromcollections,然后遍历它。
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.
但是,根据您想要执行的操作,从您的 dict 中迭代排序的键列表可能更容易。
回答by Tom Teman
Python 2.7 (released on July 3rd, 2010) supports an ordered dictionary type:
Python 2.7(2010 年 7 月 3 日发布)支持有序字典类型:

