Sorting a dictionary (with date keys) in Python

后端 未结 6 867
轮回少年
轮回少年 2020-12-29 23:40

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

相关标签:
6条回答
  • 2020-12-29 23:55

    Dictionaries are unsortable. Iterate over sorted(mydict.keys()) instead.

    0 讨论(0)
  • 2020-12-29 23:56

    Python 2.7 (released on July 3rd, 2010) supports an ordered dictionary type:

    http://www.python.org/download/releases/2.7/

    0 讨论(0)
  • 2020-12-30 00:04

    I'm sure that python knows how to compare dates. So:

    def sortedDictValues(adict):
     items = adict.items()
     items.sort()
     return [value for key, value in items]
    
    0 讨论(0)
  • 2020-12-30 00:06

    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.

    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
    
    0 讨论(0)
  • 2020-12-30 00:13

    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})]
    
    0 讨论(0)
  • 2020-12-30 00:17

    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.

    from collections import OrderedDict
    
    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.

    0 讨论(0)
提交回复
热议问题