I am trying to transform a for loop in a list comprehension but I keep getting a syntax error. What am I doing wrong?
The for loop:
for item in items:
if item in default_items.keys():
total += default_items[item]
The list comprehension:
[total := total + default_items[item] if item in default_items.keys() for item in items]
Here some example of the code in context:
items = []
total = 0
default_items = {"tophat": 2, "bowtie": 4, "monocle": 5}
items.append("bowtie")
items.append("jacket")
items.append("monocle")
items.append("chocolate")
for item in items:
if item in default_items.keys():
total += default_items[item]
print(total) # 9
items = []
total = 0
[total := total + default_items[item] if item in default_items.keys() for item in items] # raising sintax error
print(total) # 9