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.
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.
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 .
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.
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.
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.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With