Search code examples
pythondictionarysorteddictionary

python, read keys from dict by size, to plot them


I have a python dict which contains unsorted key/value pairs, where the key is a datetime and the value is an int.

{"1.12.2015":5, "4.12.2015":3, "2.12.2015":6, ...}

I now wish to read the keys, and their values sorted by date in order to plot them using pyplot.

The result should be like:

first pair:
1.12.2015 : 5
second: 
2.12.2015 : 6
third:
4.12.2015 : 3

the question is, what is the best way to get the dates and values out in the right order. It would be best if there was an option which runs in python 2.6


Solution

  • Is this more or less what you are looking for?

    data = {"1.12.2015":5, "4.12.2015":3, "2.12.2015":6}
    
    from datetime import datetime
    
    for k,v in sorted([(datetime.strptime(k, '%d.%m.%Y'), v) for k,v in data.iteritems()]):
        print datetime.strftime(k, '%d.%m.%Y'), v