How to sort over dictionaries

John Ladasky john_ladasky at sbcglobal.net
Wed Aug 29 01:50:09 EDT 2018


The top-level object you are showing is a list [], not a dictionary {}.  It has dictionaries inside of it though.  Do you want to sort the list?

Python's sorted() function returns a sorted copy of a sequence.  Sorted() has an optional argument called "key".  Key accepts a second function which can be used to rank each element in the event that you don't want to compare them directly.  

The datetime module has functions which can convert the time strings you are showing into objects which are ordered by time and are suitable as keys for sorting.  Look at datetime.datetime.strptime().  It takes two arguments, the date/time string, and a second string describing the format of the first string.  There are many ways to format date and time information as strings and none are standard.  This function call seems to work for your data:

>>> datetime.strptime("04-08-2018 19:12", "%d-%m-%Y %H:%M")
datetime.datetime(2018, 8, 4, 19, 12)

Hope that gets you started.



More information about the Python-list mailing list