Reputation: 68
I've built a for loop that goes through the values of a list, enters them as keys for two dictionaries and multiplies the 2 key values together.
When you print, it gives each multiplied value on a new line.
I'd like to add the values together to get a combined total but thus far have not been able to.
#The list and two dictionaries
List1 = ['coffee', 'tea' , 'cake' , 'scones' ]
Dictionary1 ={'coffee' :'4', 'tea' :'2' , 'cake' :'6' , 'scones' :'8' }
Dictionary2 = { 'coffee':'25' , 'tea':'18' , 'cake':'45' , 'scones':'30' }
#the for function which runs through the list
for i in range(len(List1)):
t = ((int(Dictionary1[List1[i]])*int(Dictionary2[List1[i]])))
#now if you print t the following is printed:
100
36
270
240
I'd like to get the sum of these values, but so far I have not been able to.
In order to do so, I've tried sum(t) which produces the error:
">TypeError: 'int' object is not iterable"
I thought that might be a concatenation error so I tried sum(int(t)) but this does not work.
I've also tried turning it into list() " x = list(t) as well as replacing the lines with commas with .replace("\n",",")
.
All feedback welcome, I think this is probably easily solved but I just haven't been able to get there - thanks.
Upvotes: 2
Views: 2048
Reputation: 6729
If I get you right and thinking in the simplest way, you can assign a variable and add up it in every iteration like:
res = 0
for i in range(len(List1)):
t = ((int(Dictionary1[List1[i]])*int(Dictionary2[List1[i]])))
res += t
print(res)
Edit: And as @patrick suggests and discussed in this post, the variable name edited not to be sum
Upvotes: 1
Reputation: 51623
The error is self explanatory: TypeError: 'int' object is not iterable
when executing t
. That means t
is just a sigular int value. The built in sum()
needs an iterable to operate on.
You need to add your int to something for each iteration:
List1 = ['coffee', 'tea' , 'cake' , 'scones' ]
Dictionary1 ={'coffee' :'4', 'tea' :'2' , 'cake' :'6' , 'scones' :'8' }
Dictionary2 = { 'coffee':'25' , 'tea':'18' , 'cake':'45' , 'scones':'30' }
# accumulate your values into s
s = 0
for i in range(len(List1)):
t = ((int(Dictionary1[List1[i]])*int(Dictionary2[List1[i]])))
s += t
print(s) # print sum
Outputs:
646
You can however create a generator comprehension and use the built in sum()
function as well:
print (sum ( int(Dictionary1[a])*int(Dictionary2[a]) for a in List1))
Upvotes: 1
Reputation: 21275
Here's a list comprehension that does the job
total = sum(int(Dictionary1[x]) * int(Dictionary2[x]) for x in List1)
Output:
646
Upvotes: 1