📌  相关文章
📜  查找字典键总和的Python程序

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

查找字典键总和的Python程序

给定一个带有整数键的字典。任务是找到所有键的总和。

例子:

Input : test_dict = {3 : 4, 9 : 10, 15 : 10, 5 : 7} 
Output : 32 
Explanation : 3 + 9 + 15 + 5 = 32, sum of keys.

Input : test_dict = {3 : 4, 9 : 10, 15 : 10} 
Output : 27 
Explanation : 3 + 9 + 15 = 27, sum of keys. 

方法#1:使用循环

这是可以执行此任务的方法之一。在这里,我们迭代字典中的所有键并使用计数器计算总和。

Python3
# Python3 code to demonstrate working of
# Dictionary Keys Summation
# Using loop
  
# initializing dictionary
test_dict = {3: 4, 9: 10, 15: 10, 5: 7, 6: 7}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
res = 0
for key in test_dict:
  
    # adding keys
    res += key
  
# printing result
print("The dictionary keys summation : " + str(res))


Python3
# Python3 code to demonstrate working of
# Dictionary Keys Summation
# Using keys() + sum()
  
# initializing dictionary
test_dict = {3: 4, 9: 10, 15: 10, 5: 7, 6: 7}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# sum() performs summation
res = sum(list(test_dict.keys()))
  
# printing result
print("The dictionary keys summation : " + str(res))


输出
The original dictionary is : {3: 4, 9: 10, 15: 10, 5: 7, 6: 7}
The dictionary keys summation : 38

方法#2:使用keys() + sum()

这是可以执行此任务的速记。在这里,我们使用keys() 提取列表中的所有键,并使用sum() 进行求和。

蟒蛇3

# Python3 code to demonstrate working of
# Dictionary Keys Summation
# Using keys() + sum()
  
# initializing dictionary
test_dict = {3: 4, 9: 10, 15: 10, 5: 7, 6: 7}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# sum() performs summation
res = sum(list(test_dict.keys()))
  
# printing result
print("The dictionary keys summation : " + str(res))
输出
The original dictionary is : {3: 4, 9: 10, 15: 10, 5: 7, 6: 7}
The dictionary keys summation : 38