Sum of value in a dictionary

Question:

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

Asked By: watermelon_soda

||

Answers:

1st Solution: you can do this using map

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

result_dict = {key: sum(map(int, value)) for key, value in dic1.items()}
print(result_dict)

Output:

{'2012-03-06': 10, '2012-03-12': 20}

2nd Solution: And convert into expected output easily

dic1 = {'2012-03-06':['1','3','5'],'2012-03-12':['7','3','10']}
for key, value in dic1.items():
    print(f"{key}, {sum(map(int, value))}")

Output:

2012-03-06, 10
2012-03-12, 20
Answered By: Usman Arshad

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

Answered By: Jason Lee