Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/traitlets/utils/nested_update.py: 23%
13 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-20 06:09 +0000
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-20 06:09 +0000
1# Copyright (c) IPython Development Team.
2# Distributed under the terms of the Modified BSD License.
3from __future__ import annotations
5from typing import Any, Dict
8def nested_update(this: Dict[Any, Any], that: Dict[Any, Any]) -> Dict[Any, Any]:
9 """Merge two nested dictionaries.
11 Effectively a recursive ``dict.update``.
13 Examples
14 --------
15 Merge two flat dictionaries:
16 >>> nested_update(
17 ... {'a': 1, 'b': 2},
18 ... {'b': 3, 'c': 4}
19 ... )
20 {'a': 1, 'b': 3, 'c': 4}
22 Merge two nested dictionaries:
23 >>> nested_update(
24 ... {'x': {'a': 1, 'b': 2}, 'y': 5, 'z': 6},
25 ... {'x': {'b': 3, 'c': 4}, 'z': 7, '0': 8},
26 ... )
27 {'x': {'a': 1, 'b': 3, 'c': 4}, 'y': 5, 'z': 7, '0': 8}
29 """
30 for key, value in this.items():
31 if isinstance(value, dict):
32 if key in that and isinstance(that[key], dict):
33 nested_update(this[key], that[key])
34 elif key in that:
35 this[key] = that[key]
37 for key, value in that.items():
38 if key not in this:
39 this[key] = value
41 return this