Sorting dictionary by datetime value

Chris Angelico rosuav at gmail.com
Tue Feb 11 03:51:17 CET 2014


On Tue, Feb 11, 2014 at 1:31 PM, pete suchsland
<visiondoctor2020 at gmail.com> wrote:
> How about make it simple by using sorted(a.values()) ...
>
>>>> a = {}
>>>> a['first'] = datetime.datetime.now()
>>>> a['second'] = datetime.datetime.now()
>>>> a['third'] = datetime.datetime.now()
>>>> a['forth'] = datetime.datetime.now()
>>>> a['fifth'] = datetime.datetime.now()
>
>>>> sorted(a.values())
> [datetime.datetime(2014, 2, 10, 19, 24, 35, 163585), datetime.datetime(2014, 2, 10, 19, 24, 53, 244532), datetime.datetime(2014, 2, 10, 19, 25, 9, 483683), datetime.datetime(2014, 2, 10, 19, 25, 25, 581743), datetime.datetime(2014, 2, 10, 19, 25, 37, 789907)]

Works nicely if you don't care about the keys. Otherwise, you need to
somehow look them back up, which is at best going to add an extra O(n)
step (creating a reverse dictionary), and at worst will require an
O(n*n) search (if the objects aren't hashable).

ChrisA



More information about the Python-list mailing list