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?
Solution 1:
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.
Solution 2:
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']
Post a Comment for "Sort Python Dictionary By Absolute Value Of Values"