Python程序查找字典中项的总和

编写一个Python程序,通过实际示例查找字典中项的总和。

Python程序查找字典中项的总和示例

在此程序中,我们使用sum函数和字典值函数来查找字典值的总和。sum函数用于返回字典中所有值的总和。

myDict = {'x': 250, 'y':500, 'z':410}
print("Dictionary: ", myDict)

# Print Values using get
print("\nSum of Values: ", sum(myDict.values()))
Python Program to find Sum of all Items in a Dictionary

使用values()计算字典中项的总和

程序使用For Loop以及values函数来添加字典中的值。

myDict = {'x': 250, 'y':500, 'z':410}
print("Dictionary: ", myDict)
total = 0

# Print Values using get
for i in myDict.values():
    total = total + i
    
print("\nThe Total Sum of Values : ", total)

字典项的总和输出。

Dictionary: {'x': 250, 'y':500, 'z':410}

The Total Sum of Values : 1240

使用for循环查找字典中项的总和

在此Python程序中,我们使用For Loop来迭代字典中的每个元素。我们在循环内将这些字典值添加到total变量中。

myDict = {'x': 250, 'y':500, 'z':410}
print("Dictionary: ", myDict)
total = 0

# Print Values using get
for i in myDict:
    total = total + myDict[i]
    
print("\nThe Total Sum of Values : ", total)
Dictionary: {'x': 250, 'y':500, 'z':410}

The Total Sum of Values : 1160