Python dictionary sumUp values
<p>The function below should return a new dictionary which has summed the values up. </p>

<pre><code>import functools
def sumUp(d):
    for k in d:
        d.update({k: functools.reduce(lambda x, y: x + y, d[k])})
    print(d)
</code></pre>

<p>When i call the function as follows i get the following <code>TypeError</code> which i can't understand why:</p>

<pre><code>sumUp({"Ungefucht": (165, 165, 165, 255, 286.25, 255, 165, 240, 240, 150), "Malsch": (120, 240, 120, 120, 120, 120, 120), "AAA": (1, 2), "Fens": (115.20, 69.60, 28.80, 50.40), "Betti": (82.50,)})
</code></pre>

<blockquote>
  <p>Traceback (most recent call last):</p>
  
  <p>File "", line 1, in </p>
  
  <p>File "/home/amir/programming/python/lern.py", line 6, in sumUp
      print(d)</p>
  
  <p>TypeError: reduce() arg 2 must support iteration</p>
</blockquote>

<p>When i omit one of the key-values it works fine:</p>

<pre><code>sumUp({"Ungefucht": (165, 165, 165, 255, 286.25, 255, 165, 240, 240, 150), "Malsch": (120, 240, 120, 120, 120, 120, 120), "AAA": (1, 2), "Fens": (115.20, 69.60, 28.80, 50.40)})
</code></pre>

<blockquote>
  <p>{'Malsch': 960, 'Ungefucht': 2086.25, 'Fens': 264.0, 'AAA': 3}</p>
</blockquote>

<p>Why is the first example with one more item not working as expected?</p>

<p>This works:</p>

<pre><code>def sumUp(d):
    new_d = {k: sum(v) for k, v in d.items()}
    print(new_d)
    return new_d
</code></pre>

<p>Keep in mind you are updating the dictionary while iterating over it, which causes all sorts of strange behavior.</p>

<p>The behavior is quite random and depends on the salting of the key's hashes (which modifies the dict order). You can't reproduce it consistently in Python 3.</p>

<p>This is your code fixed:</p>

<pre><code>def sumUp2(d):
    for k in d:
        d[k] = functools.reduce(lambda x, y: x + y, d[k])
    print(d)
</code></pre>

<p>It sets the key instead of updating the dict, which is safe.</p>

python python-3.x dictionary