How to sort over dictionaries
David Raymond
David.Raymond at tomtom.com
Thu Aug 30 09:55:37 EDT 2018
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.com at python.org] On Behalf Of harish at moonshots.co.in
Sent: Thursday, August 30, 2018 4:31 AM
To: python-list at 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
More information about the Python-list
mailing list