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

How to sort over dictionaries

harish at moonshots.co.in wrote:

> 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.