4

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}
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
random-xyz
  • 137
  • 4
  • 14

2 Answers2

3

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
  • Thanks so much for your help! I just wanted to know if there's a way to do it. I'll go with the for loop version per your advice. – random-xyz Nov 20 '19 at 15:08
3

You can't assign/reassign to a key within dict comprehension.
A single traversal is anyway better than potential one-liners with 2 traversals:

A more simplified/concise version:

def sum_odd_even_numbers(lst):
  d = {"even": 0, "odd": 0}
  for val in lst:
      d['even' if val % 2 == 0 else 'odd'] += val
  return d

print(sum_odd_even_numbers([2,4,5,7,8]))   # {'even': 14, 'odd': 12}
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105