📌  相关文章
📜  Python – 按值求和对字典进行排序

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

Python – 按值求和对字典进行排序

给出一个带有值列表的字典,通过值列表中的值的总和对键进行排序。

方法 #1:使用 sorted() + 字典理解 + sum()

上述功能的组合可以用来解决这个问题。在此,我们首先使用 sum() 对所有列表元素求和,然后下一步是根据使用 sorted() 提取的总和对所有键进行排序。

Python3
# Python3 code to demonstrate working of 
# Sort Dictionary by Values Summation
# Using dictionary comprehension + sum() + sorted()
  
# initializing dictionary
test_dict = {'Gfg' : [6, 7, 4], 'is' : [4, 3, 2], 'best' : [7, 6, 5]} 
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# summing all the values using sum()
temp1 = {val: sum(int(idx) for idx in key) 
           for val, key in test_dict.items()}
  
# using sorted to perform sorting as required
temp2 = sorted(temp1.items(), key = lambda ele : temp1[ele[0]])
  
# rearrange into dictionary
res = {key: val for key, val in temp2}
          
# printing result 
print("The sorted dictionary : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Sort Dictionary by Values Summation
# Using map() + dictionary comprehension + sorted() + sum()
  
# initializing dictionary
test_dict = {'Gfg' : [6, 7, 4], 'is' : [4, 3, 2], 'best' : [7, 6, 5]} 
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# summing all the values using sum()
# map() is used to extend summation to sorted()
temp = {key: sum(map(lambda ele: ele, test_dict[key])) for key in test_dict}
res = {key: temp[key] for key in sorted(temp, key = temp.get)}        
  
# printing result 
print("The sorted dictionary : " + str(res))


输出
The original dictionary is : {'Gfg': [6, 7, 4], 'is': [4, 3, 2], 'best': [7, 6, 5]}
The sorted dictionary : {'is': 9, 'Gfg': 17, 'best': 18}

方法 #2:使用 map() + 字典理解 + sorted() + sum()

上述功能的组合可以用来解决这个问题。在此,我们使用 map() 执行映射求和逻辑的任务。

Python3

# Python3 code to demonstrate working of 
# Sort Dictionary by Values Summation
# Using map() + dictionary comprehension + sorted() + sum()
  
# initializing dictionary
test_dict = {'Gfg' : [6, 7, 4], 'is' : [4, 3, 2], 'best' : [7, 6, 5]} 
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# summing all the values using sum()
# map() is used to extend summation to sorted()
temp = {key: sum(map(lambda ele: ele, test_dict[key])) for key in test_dict}
res = {key: temp[key] for key in sorted(temp, key = temp.get)}        
  
# printing result 
print("The sorted dictionary : " + str(res)) 
输出
The original dictionary is : {'Gfg': [6, 7, 4], 'is': [4, 3, 2], 'best': [7, 6, 5]}
The sorted dictionary : {'is': 9, 'Gfg': 17, 'best': 18}