Sort Python dict by datetime value
Question:
I have a Python dictionary like this:
{
'apple': datetime.datetime(2012, 12, 20, 0, 0, tzinfo=<UTC>),
'orange': datetime.datetime(2012, 2, 4, 0, 0, tzinfo=<UTC>),
'raspberry': datetime.datetime(2013, 1, 9, 0, 0, tzinfo=<UTC>)
}
What is the best way to sort the dictionary by the datetime values? I am looking for a list output with the keys in order from most recent to oldest.
Answers:
You could sort the keys like this:
sorted(dct, key=dct.get)
See the Sorting Mini-HOW TO for an explanation of this and other techniques for sorting.
Bearing in mind that the question asks how to sort by the datetime values, here’s a possible answer:
sorted(dct.items(), key=lambda p: p[1], reverse=True)
=> [('raspberry', datetime.datetime(2013, 1, 9, 0, 0)),
('apple', datetime.datetime(2012, 12, 20, 0, 0)),
('orange', datetime.datetime(2012, 2, 4, 0, 0))]
If you’re only interested in the keys:
[k for k, v in sorted(dct.items(), key=lambda p: p[1], reverse=True)]
=> ['raspberry', 'apple', 'orange']
It is really easy, you just do, something like:
from operator import itemgetter
sorted(a.items(),key=itemgetter(1),reverse=True)
Try getting list of keys as below for dictionary dict
:
[item[0] for item in sorted(dict.items(), key=lambda val: val[1])]
I have a Python dictionary like this:
{
'apple': datetime.datetime(2012, 12, 20, 0, 0, tzinfo=<UTC>),
'orange': datetime.datetime(2012, 2, 4, 0, 0, tzinfo=<UTC>),
'raspberry': datetime.datetime(2013, 1, 9, 0, 0, tzinfo=<UTC>)
}
What is the best way to sort the dictionary by the datetime values? I am looking for a list output with the keys in order from most recent to oldest.
You could sort the keys like this:
sorted(dct, key=dct.get)
See the Sorting Mini-HOW TO for an explanation of this and other techniques for sorting.
Bearing in mind that the question asks how to sort by the datetime values, here’s a possible answer:
sorted(dct.items(), key=lambda p: p[1], reverse=True)
=> [('raspberry', datetime.datetime(2013, 1, 9, 0, 0)),
('apple', datetime.datetime(2012, 12, 20, 0, 0)),
('orange', datetime.datetime(2012, 2, 4, 0, 0))]
If you’re only interested in the keys:
[k for k, v in sorted(dct.items(), key=lambda p: p[1], reverse=True)]
=> ['raspberry', 'apple', 'orange']
It is really easy, you just do, something like:
from operator import itemgetter
sorted(a.items(),key=itemgetter(1),reverse=True)
Try getting list of keys as below for dictionary dict
:
[item[0] for item in sorted(dict.items(), key=lambda val: val[1])]