Merge two nested dictionaries. Effectively a recursive ``dict.update``. Examples -------- Merge two flat dictionaries: >>> nested_update( ... {'a': 1, 'b': 2}, ... {'b': 3, 'c': 4} ... ) {'a': 1, 'b': 3, 'c': 4} Merge two nested dictionaries: >>
(this: dict[Any, Any], that: dict[Any, Any])
| 6 | |
| 7 | |
| 8 | def nested_update(this: dict[Any, Any], that: dict[Any, Any]) -> dict[Any, Any]: |
| 9 | """Merge two nested dictionaries. |
| 10 | |
| 11 | Effectively a recursive ``dict.update``. |
| 12 | |
| 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} |
| 21 | |
| 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} |
| 28 | |
| 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] |
| 36 | |
| 37 | for key, value in that.items(): |
| 38 | if key not in this: |
| 39 | this[key] = value |
| 40 | |
| 41 | return this |
no outgoing calls
no test coverage detected
searching dependent graphs…