Nested data
Real data is usually nested: a list of records, where each record is a dict that may hold lists of its own. Read it one layer at a time.
orders = [
{"id": 1, "items": ["tea", "jam"],
"total": 7.5},
{"id": 2, "items": ["milk"],
"total": 2.0},
]
print(orders[0]["items"][1]) # jam
print(sum(o["total"] for o in orders))
for order in orders:
print(order["id"], len(order["items"]))orders[0]is a dict,orders[0]["items"]is a list, and[1]picks from that list. Each step works on the result of the one before.- When you are lost, print one level, such as
orders[0], and look at its shape. - Use
record.get("key", default)when some records may lack a field. - A dict you take out of the list is the same object as the one inside it, so changing it changes the list's data too.
Write small functions that each walk one level. They are easier to test than one long expression.
Your task
Each item is a dict with "name", "price", "qty" and sometimes "tags" (a list of strings). Write stock_value(items) returning the sum of price times qty, and names_tagged(items, tag) returning the names of items whose tags include tag, in order, treating a missing "tags" as no tags.
The explanation opens here once every check passes.