Hi guys. Here we are going to learn about How to sum Dictionary Values in Python. We can easily get the sum of the dictionary by using some methods. I am giving here some easy and simple methods which will solve your problem and give you the sum of the dictionary. So lets learn this, I hope this will help you.
Contents
How to sum Dictionary Values in Python
- Sum Dictionary Values in Python
to sum Dictionary Values in Python just Use sum(). You can use sum() function to get the sun of the dictionary values in python. Just make your dictionary and use the sum() and print it. It will give you the sum of the dictionary in python.
mydict = {'maths' : 95,'science' : 98,'english' : 90} print(sum(mydict.values()))
Output :283
- How to sum Dictionary Values in Python
to sum Dictionary Values in Python just Use for loop. By using for loop you can get the sum of the dictionary in python. First of all make your dict and use for loop and print the total it will give you the sum of the dictionary's values.
mydict = {'maths' : 95,'science' : 98,'english' : 90} total = 0 for i in mydict.values(): total += i print(total)
Output :283
Method 1: Use sum()
You can use sum() function to get the sun of the dictionary values in python. Just make your dictionary and use the sum() and print it. It will give you the sum of the dictionary in python.
mydict = {'maths' : 95,'science' : 98,'english' : 90}
print(sum(mydict.values()))
Output :
283
Method 2: Use for loop
By using for loop you can get the sum of the dictionary in python. First of all make your dict and use for loop and print the total it will give you the sum of the dictionary’s values.
mydict = {'maths' : 95,'science' : 98,'english' : 90}
total = 0
for i in mydict.values():
total += i
print(total)
Output :
283
Method 3: Use itervalues()
You can use itervalues() to get the sum of the dictionary in python. Just import sys and then make your dict and use def function and use sum(itervalues) and print it. It will give you the sum of the dict as you can see in my output. So lets learn this by given below example:
import sys
mydict = {'maths' : 95,'science' : 98,'english' : 90}
def itervalues(mydict):
return iter(getattr(mydict, ('itervalues', 'values')[sys.version_info[0]>2])())
a = sum(itervalues(mydict))
print(a)
Output :
283
Method 3: Use functools.reduce() and lambda
Here i am using functools.reduce() and lambda tp get the sum of the dictionary in python. First of all import functools and then make your dictionary and use funtools.reduce to get the sum of the dictionary. With these function you have to also use lambda function like given in below method.
import functools
mydict = {'maths' : 95,'science' : 98,'english' : 90}
s = functools.reduce(lambda acc,k: acc+mydict[k], mydict, 0)
print(s)
Output :
283
Conclusion
Hope all 6 Method Are Useful For You. Comment Below Which Method You Used To Convert String To Datetime In Python. Thank You.