Search code examples
pythonstringdictionaryintegeraddition

Sum of value in a dictionary


I’m new here. I wanted to sum all the values inside a dictionary, but my values are all strings, I don’t know how to convert the strings to integers… I really appreciate if anyone can help with it!

Here’s the dictionary with code:

dic1 = dict()
dic1 = {'2012-03-06':['1','4','5'],'2012-03-12':['7','3','10']}

for i in dic1:
    print(i,’,’,sum(dic1[i]))

I want the output to be like this:

2012-03-06, 10 2012-03-12, 20


Solution

  • It can be

    dic1 = dict() 
    dic1 = {'2012-03-06':['1','4','5'],'2012-03-12':['7','3','10']} 
    for i in dic1: 
        print(i+','+ str(sum(map(int, dic1[i]))))
    

    In python3, map(func,iter) returns an iterator(list, tuple etc.) of the results after applying the given function to each item of a given iterable