I'm creating a simple function that takes a list of numbers and returns a dictionary with the sum of all the odd and even numbers.
I'm able to do so with a traditional for
loop, so I was wondering if there's a way to do the same using a dictionary comprehension. I tried, but I can't find a way to increment each value inside the comprehension using +=
.
Here's my code with a for
loop:
def sum(a):
results = {"even":0, "odd":0}
for val in a:
if val % 2 == 0:
results["even"] += val
elif val % 2 != 0:
results["odd"] += val
This was my attempt using a dictionary comprehension:
def sum(a):
results = {even:+=x if x % 2 == 0 else "odd" for x in a}