title: How can I merge two dictionaries where their trees have a matching key?
body: <p>I'd like to merge these two dicts where they meet, on the &quot;family&quot; key. I'm working on a recursive function to make the merge happen but I wonder if there isn't a better way. I was looking at collections.chainmap and it seemed close that what I'm doing but perhaps overkill.</p>
  <p>Input:</p>
  <pre><code>xe-3/0/2:
    description:
    unit:
      '0':
        family:
          inet4:
              address: 10.0.0.1
  xe-3/0/2:
    description:
    unit:
      '0':
        family:
          inet6:
              address: FE80::
  </code></pre>
  <p>Output:</p>
  <pre><code>xe-3/0/2:
    description:
    unit:
      '0':
        family:
          inet4:
              address: 10.0.0.1
          inet6:
              address: FE80::
  </code></pre>
  <p>I'm trying to get better at python by using more tricks and built-in functions but I don't think I have the right approach for discovering what I can do instead of stacking a bunch of for loops.</p>
  <p>Thanks,</p>
  <p>EDIT:</p>
  <p>This function works perfectly for my case, with the following assumptions:</p>
  <p>D1 will always be deeper and wider.
  D2 will always have a single tree.</p>
  <pre><code>def join_dicts(d1, d2):
    def recurse_join(d1, d2):
      if not isinstance(d1, dict) and not isinstance(d2, dict):
          return [d1, d2]
      if not isinstance(d1, dict):
          return {**{d1 : &quot;&quot;}, **d2}
      if not isinstance(d2, dict):
          return {**d1, **{d2 : &quot;&quot;}}
  
      for key in d2:
          if key not in d1:
              return {**d1, **d2}
          else:
              d1[key] = recurse_join(d1[key], d2[key])
      return d1
  return recurse_join(d1, d2)
  </code></pre>