Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 439
Mike R Avatar asked May 14 '17 04:05

Mike R


People also ask

Can you sort dictionaries by value in Python?

You can now sort a dictionary by value despite not having a built-in method or function to use in Python. However, there's something that raised my curiosity when I was preparing to write this article. Remember we were able to use sorted() directly on a dictionary.

How do you sort a dictionary numerically in Python?

To sort a dictionary by value in Python you can use the sorted() function. Python's sorted() function can be used to sort dictionaries by key, which allows for a custom sorting method. sorted() takes three arguments: object, key, and reverse .

Can you sort values in a dictionary?

It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.

How do you sort a dictionary based on value descending?

Sorting a dict by value descending using list comprehension. The quickest way is to iterate over the key-value pairs of your current dict and call sorted passing the dictionary values and setting reversed=True . If you are using Python 3.7, regular dict s are ordered by default.


2 Answers

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.

like image 166
Simeon Visser Avatar answered Oct 22 '22 07:10

Simeon Visser


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']
like image 39
juanpa.arrivillaga Avatar answered Oct 22 '22 06:10

juanpa.arrivillaga