nested_update.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. # Copyright (c) IPython Development Team.
  2. # Distributed under the terms of the Modified BSD License.
  3. from __future__ import annotations
  4. from typing import Any, Dict
  5. def nested_update(this: Dict[Any, Any], that: Dict[Any, Any]) -> Dict[Any, Any]:
  6. """Merge two nested dictionaries.
  7. Effectively a recursive ``dict.update``.
  8. Examples
  9. --------
  10. Merge two flat dictionaries:
  11. >>> nested_update(
  12. ... {'a': 1, 'b': 2},
  13. ... {'b': 3, 'c': 4}
  14. ... )
  15. {'a': 1, 'b': 3, 'c': 4}
  16. Merge two nested dictionaries:
  17. >>> nested_update(
  18. ... {'x': {'a': 1, 'b': 2}, 'y': 5, 'z': 6},
  19. ... {'x': {'b': 3, 'c': 4}, 'z': 7, '0': 8},
  20. ... )
  21. {'x': {'a': 1, 'b': 3, 'c': 4}, 'y': 5, 'z': 7, '0': 8}
  22. """
  23. for key, value in this.items():
  24. if isinstance(value, dict):
  25. if key in that and isinstance(that[key], dict):
  26. nested_update(this[key], that[key])
  27. elif key in that:
  28. this[key] = that[key]
  29. for key, value in that.items():
  30. if key not in this:
  31. this[key] = value
  32. return this