📜  Python – 按值差排序字典

📅  最后修改于: 2022-05-13 01:55:20.962000             🧑  作者: Mango

Python – 按值差排序字典

有时,在使用Python字典时,我们可能会遇到需要根据各种因素对项目进行排序的问题。其中之一可以是基于对偶值列表的绝对差异。这可能发生在Python > 3.6 中,因为字典是有序的。这种问题可能出现在数据域中。让我们讨论一种可以解决这个问题的方法。

方法:使用sorted() + lambda + abs() + 字典理解
上述功能的组合可以用来解决这个问题。在此,我们使用 sorted() 执行排序任务,lambda函数用于提供逻辑,abs()函数用于计算绝对差。

# Python3 code to demonstrate working of 
# Sort Dictionary by Value Difference
# Using sorted() + lambda + abs() + dictionary comprehension
  
# initializing dictionary
test_dict = {'gfg' : [34, 87],
              'is' : [10, 13], 
              'best' : [19, 27], 
              'for' : [10, 50], 
              'geeks' : [15, 45]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# Sort Dictionary by Value Difference
# Using sorted() + lambda + abs() + dictionary comprehension
res = dict(sorted(test_dict.items(), key = lambda sub: abs(sub[1][0] - sub[1][1])))
  
# printing result 
print("The sorted dictionary : " + str(res)) 
输出 :