Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting a list of dictionary values by date in python

Tags:

python

I have a list and I am appending a dictionary to it as I loop through my data...and I would like to sort by one of the dictionary keys.

ex:

data = "data from database" list = [] for x in data:      dict = {'title':title, 'date': x.created_on}      list.append(dict) 

I want to sort the list in reverse order by value of 'date'

like image 881
Joe Avatar asked Mar 16 '09 21:03

Joe


People also ask

How do I sort a list by date in Python?

To sort a Python date string list using the sort function, you'll have to convert the dates in objects and apply the sort on them. For this you can use the key named attribute of the sort function and provide it a lambda that creates a datetime object for each date and compares them based on this date object.

How do I sort a list of dictionaries in Python?

To sort a list of dictionaries according to the value of the specific key, specify the key parameter of the sort() method or the sorted() function. By specifying a function to be applied to each element of the list, it is sorted according to the result of that function.

Can you sort dictionary values in Python?

We can sort lists, tuples, strings, and other iterable objects in python since they are all ordered objects. Well, as of python 3.7, dictionaries remember the order of items inserted as well. Thus we are also able to sort dictionaries using python's built-in sorted() function.

Can we sort dictionary values?

It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.


1 Answers

You can do it this way:

list.sort(key=lambda item:item['date'], reverse=True) 
like image 179
hvintus Avatar answered Sep 16 '22 21:09

hvintus