Mike R
Mike R

Reputation: 368

Sort Python Dictionary by Absolute Value of Values

Trying to build off of the advice on sorting a Python dictionary here, how would I go about printing a Python dictionary in sorted order based on the absolute value of the values?

I have tried:

sorted(mydict, key=abs(mydict.get))

But this raises the error bad operand type for abs(): 'builtin_function_or_method' abs() expects a number, not a function. Also, abs() is the return value of the function abs, and key is just expecting a function.

Upvotes: 6

Views: 5631

Answers (2)

Simeon Visser
Simeon Visser

Reputation: 122376

You can use:

sorted(mydict, key=lambda dict_key: abs(mydict[dict_key]))

This uses a new function (defined using lambda) which takes a key of the dictionary and returns the absolute value of the value at that key.

This means that the result will be sorted by the absolute values that are stored in the dictionary.

Upvotes: 9

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95993

You need to compose the application by wrapping in another function, so instead of this:

>>> d = {'a':1,'b':-2,'c':3,'d':-4}
>>> sorted(d, key=d.get)
['d', 'b', 'a', 'c']

You can can use function composition (in this case using a lambda):

>>> sorted(d, key=lambda k: abs(d[k]))
['a', 'b', 'c', 'd']

Upvotes: 3

Related Questions