Remember to check what the res["date"] types actually are. If they're just text, then it looked like they were in M/D/Y format, which won't sort correctly as text, hence you might want to include using datetime.strptime() to turn them into sortable datetimes.
-----Original Message----- From: Python-list [mailto:python-list-bounces+david.raymond=tomtom....@python.org] On Behalf Of har...@moonshots.co.in Sent: Thursday, August 30, 2018 4:31 AM To: python-list@python.org Subject: Re: How to sort over dictionaries > > sort = sorted(results, key=lambda res:itemgetter('date')) > > print(sort) > > > > > > I have tried the above code peter but it was showing error like .... > > TypeError: '<' not supported between instances of 'operator.itemgetter' > > and 'operator.itemgetter' > > lambda res: itemgetter('date') > > is short for > > def keyfunc(res): > return itemgetter('date') > > i. e. it indeed returns the itemgetter instance. But you want to return > res["date"]. For that you can either use a custom function or the > itemgetter, but not both. > > (1) With regular function: > > def keyfunc(res): > return res["date"] > sorted_results = sorted(results, key=keyfunc) > > (1a) With lambda: > > keyfunc = lambda res: res["date"] > sorted_results = sorted(results, key=keyfunc) > > (2) With itemgetter: > > keyfunc = itemgetter("date") > sorted_results = sorted(results, key=keyfunc) > > Variants 1a and 2 can also be written as one-liners. Thanks Peter....No 2 has worked. -- https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list