title: Adding dictionaries recursively in Python
body: <p>I have the following two functions which take two dictionaries and recursively add their values.</p>
  
  <pre><code>def recursive_dict_sum_helper(v1, d2, k):
      try: v2 = d2[k]
      except KeyError: return v1 #problem is here if key not found it just return value but what about rest of the keys which is in d2??
  
      if not v1: return v2
      # "add" two values: if they can be added with '+', then do so,
      # otherwise expect dictionaries and treat them appropriately.
      try:
          if type(v1) == list and type(v2) == list:
              v1.extend(v2)
              return list(set(v1))
          else:
              return v1 + v2
      except: return recursive_dict_sum(v1, v2)
  
  def recursive_dict_sum(d1, d2):
      if len(d1) &lt; len(d2):
          temp = d1
          d1 = d2
          d2 = temp
      # Recursively produce the new key-value pair for each
      # original key-value pair, and make a dict with the results.
      return dict(
          (k, recursive_dict_sum_helper(v, d2, k))
          for (k, v) in d1.items()
      )
  </code></pre>
  
  <p>If I give the following input then the output is fine which I am expecting:</p>
  
  <pre><code>a = {'abc': {'missing': 1, 'modified': 0, 'additional': 2}}
  b = {'abc': {'missing': 1, 'modified': 1, 'additional': 2}}
  
  mn = recursive_dict_sum(a, b)
  
  output: mn = {'abc': {'missing': 2, 'modified': 1, 'additional': 4}}
  </code></pre>
  
  <p>but if the input is:</p>
  
  <pre><code>a = {'abc': {'missing': 1, 'modified': 0, 'additional': 2}}
  b = {'cde': {'missing': 1, 'modified': 1, 'additional': 2}}
  
  output: {'abc': {'missing': 1, 'modified': 0, 'additional': 2}} #which is wrong
  </code></pre>
  
  <p>If there is no key found in the 2nd dictionary it returns key value from first dictionary. So it is operating on one dictionary items, what about the rest of keys in the second dictionary? How can I update the above script so that the output would be:</p>
  
  <pre><code>output: {'abc': {'missing': 1, 'modified': 0, 'additional': 2}, 'cde': {'missing': 1, 'modified': 1, 'additional': 2}}
  </code></pre>