[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

How to sort over dictionaries

harish at moonshots.co.in wrote:

> On Wednesday, August 29, 2018 at 11:20:26 AM UTC+5:30, John Ladasky wrote:
>> 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.
> i have tried but it was showing error like this....
> TypeError: '<' not supported between instances of 'operator.itemgetter'
> and 'operator.itemgetter'

Please remember to always provide the code you tried. That makes it easier 
to point out the error.

That said, here's a typical example of sorted and operator.itemgetter:

>>> import operator
>>> data = [dict(foo=1, bar="second"), dict(foo=2, bar="first")]
>>> sorted(data, key=operator.itemgetter("foo"))
[{'bar': 'second', 'foo': 1}, {'bar': 'first', 'foo': 2}]
>>> sorted(data, key=operator.itemgetter("bar"))
[{'bar': 'first', 'foo': 2}, {'bar': 'second', 'foo': 1}]