按值的绝对值对Python字典进行排序 [英] Sort Python Dictionary by Absolute Value of Values

查看:462
本文介绍了按值的绝对值对Python字典进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在有关排序Python字典的建议的基础上在此,我将如何打印Python字典是否根据值的绝对值排序?

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?

我尝试过:

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

但这会引发错误bad operand type for abs(): 'builtin_function_or_method' abs()需要一个数字,而不是一个函数.另外,abs()是函数abs的返回值,而key只是期望一个函数.

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.

推荐答案

您可以使用:

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

这使用了一个新函数(使用lambda定义),该函数获取字典的一个键并返回该键的值的绝对值.

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.

这篇关于按值的绝对值对Python字典进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆