Home > Backend Development > Python Tutorial > How to Update a Nested Dictionary in Python While Preserving Specific Values at Different Depths?

How to Update a Nested Dictionary in Python While Preserving Specific Values at Different Depths?

Linda Hamilton
Release: 2024-11-12 03:58:02
Original
1055 people have browsed it

How to Update a Nested Dictionary in Python While Preserving Specific Values at Different Depths?

Nested Dictionary Update with Depth Preservation

In Python, updating a nested dictionary can be tricky, especially when you want to merge its contents with another dictionary while preserving specific values at different depths. Consider the following scenario:

Given two dictionaries, dictionary1 and update, how can we update dictionary1 with the contents of update without overwriting a particular value at the deepest level (e.g., "levelA") while updating all other values?

dictionary1 = {
    "level1": {
        "level2": {"levelA": 0, "levelB": 1}
    }
}
update = {
    "level1": {
        "level2": {"levelB": 10}
    }
}
Copy after login

If we simply use the update method, it overwrites the entire "level2" subdictionary, losing the "levelA" value:

dictionary1.update(update)
print(dictionary1)
Copy after login
{
    "level1": {
        "level2": {"levelB": 10}
    }
}
Copy after login

To tackle this challenge, we need a recursive solution that considers the variable depth of the dictionaries and merges values appropriately.

Recursive Solution:

The following code implements a recursive "partial update" function that updates dictionary values without overwriting specified keys:

import copy

def partial_update(d, u, preserve):
    for k, v in u.items():
        if isinstance(v, dict):
            if d.get(k, None) is None:
                d[k] = copy.deepcopy(v)
            else:
                partial_update(d[k], v, preserve)
        elif k in preserve:
            continue
        else:
            d[k] = copy.deepcopy(v)
    return d
Copy after login

The partial_update function takes three arguments:

  • d: The dictionary to update
  • u: The dictionary containing the updates
  • preserve: A list of keys to preserve from overwriting

To preserve the "levelA" value in our example, we can use the following code:

partial_update(dictionary1, update, ["levelA"])
print(dictionary1)
Copy after login
{
    "level1": {
        "level2": {"levelA": 0, "levelB": 10}
    }
}
Copy after login

In this solution, we make a copy of the dictionaries before updating to prevent unexpected modifications. This ensures that the original dictionaries remain intact even after the partial update.

The above is the detailed content of How to Update a Nested Dictionary in Python While Preserving Specific Values at Different Depths?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template