Reputation: 452
I have a dictionary that contains lists in it like the one below:
a = {'Dairy-Milk': ['Dairy-Milk', '12345', '800', 1], 'test': ['test', '1111', '600', 1]}
I want to go through the dictionary perform multiplication for (each_dictionary_Item[2] * each_dictionary_Item[3]) then get the total sum from all the items.
From my little knowledge, I have called a.get_keys then I have gone through for each item in the key,and called list pos 2 * 3, then appended that to another list in which I get the sum of the entire list using sum(list)....this gives me incorrect sums when new items are added.
for item in self.listofKeys:
thequantity = self.productList[item][3]
thecash = self.productList[item][2]
multiplied = float(thequantity) * float(thecash)
self.thesumsList.append(multiplied)
self.ids.thetotal.text = "Total Payable: " + str(sum(self.thesumsList))
Is there a cleaner way to achieve what I want? (get sum of every item in list list[3] * list[3])
Upvotes: 0
Views: 33
Reputation: 77857
Yes: iterate over the values themselves, pulling out the desired product from each. Feed that result to sum
directly as a generator.
sum(entry[2] * entry[3] for entry in a.values())
Upvotes: 2