title: Recursive diff of two dictionaries (keys and values)?
body: <p>So I have a python dictionary, call it <code>d1</code>, and a version of that dictionary at a later point in time, call it <code>d2</code>. I want to find all the changes between <code>d1</code> and <code>d2</code>. In other words, everything that was added, removed or changed. The tricky bit is that the values can be ints, strings, lists, or dicts, so it needs to be recursive. This is what I have so far:</p>
  
  <pre><code>def dd(d1, d2, ctx=""):
      print "Changes in " + ctx
      for k in d1:
          if k not in d2:
              print k + " removed from d2"
      for k in d2:
          if k not in d1:
              print k + " added in d2"
              continue
          if d2[k] != d1[k]:
              if type(d2[k]) not in (dict, list):
                  print k + " changed in d2 to " + str(d2[k])
              else:
                  if type(d1[k]) != type(d2[k]):
                      print k + " changed to " + str(d2[k])
                      continue
                  else:
                      if type(d2[k]) == dict:
                          dd(d1[k], d2[k], k)
                          continue
      print "Done with changes in " + ctx
      return
  </code></pre>
  
  <p>It works just fine unless the value is a list. I cant quite come up with an elegant way to deal with lists, without having a huge, slightly changed version of this function repeated after a <code>if(type(d2) == list)</code>. </p>
  
  <p>Any thoughts?</p>
  
  <p>EDIT: This differs from <a href="https://stackoverflow.com/questions/4197312/diff-multidimensional-dictionaries-in-python" title="this post">this post</a> because the keys can change</p>