I tried reading through many similar questions (this seemed closest: Python sum dict values based on keys) but still struggling to answer the following question below. Boiling it down to basics
I have the following 3 dictionaries with lists as keys:
{'milk': ['gallons', 5, 10, 50]}
{'eggs': ['cartons', 5, 2, 10]}
{'bacon': ['packages', 5, 7, 35]}
I want to be able to sum the last value of each nested list and have an expected, single value of 95
printed to the screen.
I've seen answers to similar questions that involve lambdas but I know there has to be a way to do this with iterating through the list. I've seen the use of sum and Counter and am open to any explanations. Thank you in advance.
UPDATE/ADDED CONTEXT
Thank you to those who have already been responding. I realize more context may be needed to answer this.
These entries are being made from this class:
class GroceryCart(dict):
def __init__(self):
self = {}
def addToCart(self, item, units, quantity, price):
item_total = quantity*price
self.update({item:[units, quantity, price, item_total]})
def returnCart(self):
return self
my_cart = GroceryCart()
That is where you are getting the funky structure of info.
I tried @ggorlan's response below but got traceback errors about not having str values to use .values()
Traceback (most recent call last):
File "grocery_store.py", line 156, in <module>
total = sum(sum(y[-1] for y in x.values()) for x in my_cart)
File "grocery_store.py", line 156, in <genexpr>
total = sum(sum(y[-1] for y in x.values()) for x in my_cart)
AttributeError: 'str' object has no attribute 'values'