简体   繁体   中英

Python3: Date strings to chronological order

I have a dictionary where the keys are date strings. The format is:

%d.%m.%Y

ie. "5.11.2008". The dates have corresponding data for each day.

What would be the easiest way to collect them in to two lists, one for the keys and one for the values, where the lists were in chronological order and keys[5] would correspond to values[5]?

What I'm ultimately trying to achieve is get those dates and values and plot them accordingly. I'm using matplotlib at the moment.

Convert the keys to datetime.date values; using .items() would give you tuples of both key and value that you can then sort:

data = [(datetime.datetime.strptime(k, '%d.%m.%Y').date(), v) 
        for k, v in yourdict.items()]
data.sort()

Then index these; data[5][0] is the date, data[5][1] is the dictionary value.

If you need to retain the original date formatting, use the date format parsing only for sorting; here's a one-liner variant of the above that uses a sort key:

data = sorted(yourdict.items(), 
              key=lambda i: datetime.datetime.strptime(i[0], '%d.%m.%Y'))

Here I use the sorted() function to do the hard work, and the key lambda takes each date string, converting it to a datetime.datetime instance for sorting purposes only. I don't limit this to a datetime.date instance as in the first example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM