Home  >  Article  >  Backend Development  >  How to Update Nested Dictionaries in Python while Preserving Existing Values?

How to Update Nested Dictionaries in Python while Preserving Existing Values?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-09 06:35:02632browse

How to Update Nested Dictionaries in Python while Preserving Existing Values?

Updating Nested Dictionaries Preserving Existing Values

In Python, updating dictionaries with nested structures can be tricky, particularly when you want to merge values without overwriting existing ones. This question explores how to update a nested dictionary dictionary1 with the contents of update, while preserving the value in levelA.

Flaws in the Original Approach

The given Python code demonstrates a common mistake:

dictionary1.update(update)

This simple update doesn't preserve levelA because the update dictionary takes precedence and overwrites the entire structure under level1.

Recursive Solution

The solution provided in the answer suggests a recursive approach that involves:

  1. Iterating through the keys and values in the update dictionary.
  2. If the value is a mapping (another dictionary), recursively call update on the corresponding sub-dictionary in the original dictionary.
  3. Otherwise, update the value as usual.

Updated Code

Here's the improved code based on the suggested answer:

def update(d, u):
    for k, v in u.items():
        if isinstance(v, collections.abc.Mapping):
            d[k] = update(d.get(k, {}), v)
        else:
            d[k] = v
    return d

dictionary1 = {
    "level1": {
        "level2": {"levelA": 0, "levelB": 1}
    }
}
update = {
    "level1": {
        "level2": {"levelB": 10}
    }
}
updated_dict = update(dictionary1, update)
print(updated_dict)

Output

{'level1': {'level2': {'levelA': 0, 'levelB': 10}}}

Explanation

This solution recursively updates the nested dictionaries, preserving the existing levelA value while updating the values under levelB as expected.

The above is the detailed content of How to Update Nested Dictionaries in Python while Preserving Existing Values?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn