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.datevalues; using.items()would give you tuples of both key and value that you can then 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:
Here I use the
sorted()function to do the hard work, and thekeylambda takes each date string, converting it to adatetime.datetimeinstance for sorting purposes only. I don’t limit this to adatetime.dateinstance as in the first example.