How to sort over dictionaries
harish at moonshots.co.in
harish at moonshots.co.in
Thu Aug 30 04:31:01 EDT 2018
> > 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.
More information about the Python-list
mailing list