Python程序查找字典中所有项目的总和
给定Python中的字典,编写一个Python程序来查找字典中所有项目的总和。
例子:
Input : {‘a’: 100, ‘b’:200, ‘c’:300}
Output : 600
Input : {‘x’: 25, ‘y’:18, ‘z’:45}
Output : 88
方法 #1:使用内置 sum()函数
使用 sum函数求字典值的总和。
Python3
# Python3 Program to find sum of
# all items in a Dictionary
# Function to print sum
def returnSum(myDict):
list = []
for i in myDict:
list.append(myDict[i])
final = sum(list)
return final
# Driver Function
dict = {'a': 100, 'b': 200, 'c': 300}
print("Sum :", returnSum(dict))
Python3
# Python3 Program to find sum of
# all items in a Dictionary
# Function to print sum
def returnSum(dict):
sum = 0
for i in dict.values():
sum = sum + i
return sum
# Driver Function
dict = {'a': 100, 'b': 200, 'c': 300}
print("Sum :", returnSum(dict))
Python3
# Python3 Program to find sum of
# all items in a Dictionary
# Function to print sum
def returnSum(dict):
sum = 0
for i in dict:
sum = sum + dict[i]
return sum
# Driver Function
dict = {'a': 100, 'b': 200, 'c': 300}
print("Sum :", returnSum(dict))
Python3
# Python3 Program to find sum of
# all items in a Dictionary
# Function to print sum
def returnSum(dict):
return sum(dict.values())
# Driver Function
dict = {'a': 100, 'b': 200, 'c': 300}
print("Sum :", returnSum(dict))
输出
Sum : 600
方法 #2:使用 For 循环使用 values()函数遍历值
使用values ()函数遍历字典的每个值并不断将其添加到总和中。
Python3
# Python3 Program to find sum of
# all items in a Dictionary
# Function to print sum
def returnSum(dict):
sum = 0
for i in dict.values():
sum = sum + i
return sum
# Driver Function
dict = {'a': 100, 'b': 200, 'c': 300}
print("Sum :", returnSum(dict))
输出
Sum : 600
方法 #3:使用 For 循环遍历 Dictionary 的项目
遍历字典的每一项并简单地将值添加到 sum 变量。
Python3
# Python3 Program to find sum of
# all items in a Dictionary
# Function to print sum
def returnSum(dict):
sum = 0
for i in dict:
sum = sum + dict[i]
return sum
# Driver Function
dict = {'a': 100, 'b': 200, 'c': 300}
print("Sum :", returnSum(dict))
输出
Sum : 600
方法#4:使用dictionary.sum() 方法查找通过dictionary.values()函数取出的值的总和。
Python3
# Python3 Program to find sum of
# all items in a Dictionary
# Function to print sum
def returnSum(dict):
return sum(dict.values())
# Driver Function
dict = {'a': 100, 'b': 200, 'c': 300}
print("Sum :", returnSum(dict))
输出
Sum : 600