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}
There is no way to one-line this efficiently. It can be one lined but then you are doing two iterations instead of one:
def sum_odd_even(a):
return {'odd': sum(x for x in a if x % 2), 'even': sum(x for x in a if x % 2 == 0)}
You are better off doing it how you are doing it now. That being said, don't name a function sum
. It is a built-in function.
You are better off looping how you are now since it only takes one iteration:
def sum_odd_even(a):
results = {"even":0, "odd":0}
for val in a:
if val % 2 == 0:
results["even"] += val
else:
results["odd"] += val