def _merge_nested_dicts_rec(original: Dict[str, Any],
                            update: Dict[str, Any],
                            prefix: str = '') -> Sequence[str]:
  """Procedure to merge two nested dictionaries."""
  unexpected = []
  for key in update:
    full_key = prefix + '/' + key
    if isinstance(update[key], dict):
      if key in original:
        assert isinstance(original[key], dict), key
        unexpected.extend(
            _merge_nested_dicts_rec(
                original[key], update[key], prefix=full_key))
      else:
        original[key] = {}
        unexpected.extend(
            _merge_nested_dicts_rec(
                original[key], update[key], prefix=full_key))
    else:
      if key not in original:
        unexpected.append(full_key)
      original[key] = update[key]

  return unexpected
Procedure to merge two nested dictionaries.
language/mentionmemory/utils/checkpoint_utils.py