How to Update a Nested Dictionary While Preserving Specific Key-Value Pairs?

Linda Hamilton
Release: 2024-11-06 17:30:03
Original
219 people have browsed it

How to Update a Nested Dictionary While Preserving Specific Key-Value Pairs?

Updating a Nested Dictionary of Varying Depth

To seamlessly update a nested dictionary (dictionary1) with the contents of another nested dictionary (update) while preserving specific key-value pairs, it is necessary to employ a recursive solution that considers the varying depths of the dictionaries.

Consider the following example scenario:

Before Update:

dictionary1 = {
    "level1": {
        "level2": {"levelA": 0, "levelB": 1}
    }
}

update = {
    "level1": {
        "level2": {"levelB": 10}
    }
}
Copy after login

Using the standard update method would overwrite the existing "level2" values in dictionary1, resulting in:

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

Recursive Solution:

To address this preservation requirement, the following Python code provides a recursive solution:

import copy

def update_dictionary(d, u):
    for k, v in u.items():
        if isinstance(v, dict):
            # If the value is a dictionary, recursively update
            d[k] = update_dictionary(d.get(k, {}), v)
        else:
            # If the value is not a dictionary, simply update
            d[k] = copy.deepcopy(v)
    return d
Copy after login

This solution creates a deep copy of the original dictionary1 to prevent in-place updates. It then iterates through the update dictionary (u) and recursively updates the corresponding values in d. If the value is a dictionary, it continues the recursion; otherwise, it updates the value directly.

Usage:

Applying this solution to the earlier example:

result = update_dictionary(dictionary1, update)
print(result)
Copy after login

Result:

{
    "level1": {
        "level2": {"levelA": 0, "levelB": 10}  # "levelA" preserved
    }
}
Copy after login

This solution effectively updates the "levelB" value while preserving the "levelA" value in the original dictionary. It handles nested dictionaries of varying depths, ensuring that specific key-value pairs are preserved during the update process.

The above is the detailed content of How to Update a Nested Dictionary While Preserving Specific Key-Value Pairs?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!