2

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.

4

1 に答える 1

4

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.

于 2012-08-02T10:46:36.947 に答える