如何修改嵌套字典中指定键对应的值?
To modify every instance of a target key across all levels of a nested dictionary, a recursive approach is perfect here—it handles any depth of nesting automatically, no matter how the dictionary is structured upfront.
Step-by-Step Solution
We’ll build a function that traverses each key-value pair:
- If the current key matches our target, update its value immediately.
- If the value is another dictionary, recursively run the same logic on that nested dictionary to check for the target key there.
In-Place Modification (Alters Original Dictionary)
This version modifies your existing dictionary directly, which is efficient if you don’t need to keep the original data:
def change_nested_key(dictionary, target_key, new_value): for key in dictionary: # Update the value if we hit the target key if key == target_key: dictionary[key] = new_value # Recurse into nested dictionaries to check deeper levels elif isinstance(dictionary[key], dict): change_nested_key(dictionary[key], target_key, new_value)
Usage with Your Example
Here’s how to apply this to your stocks dictionary:
stocks = { 'name': 'stocks', 'IBM': 146.48, 'MSFT': 44.11, 'CSCO': 25.54, 'micro': {'name': 'micro', 'age': 1} } # Update all 'name' keys to 'test' change_nested_key(stocks, "name", "test") print(stocks)
Output:
{ 'name': 'test', 'IBM': 146.48, 'MSFT': 44.11, 'CSCO': 25.54, 'micro': {'name': 'test', 'age': 1} }
Immutable Version (Preserves Original Dictionary)
If you want to keep the original dictionary intact, use this version that returns a new modified copy instead:
def change_nested_key_immutable(dictionary, target_key, new_value): new_dict = {} for key, value in dictionary.items(): if key == target_key: new_dict[key] = new_value elif isinstance(value, dict): new_dict[key] = change_nested_key_immutable(value, target_key, new_value) else: new_dict[key] = value return new_dict # Usage: updated_stocks = change_nested_key_immutable(stocks, "name", "test")
Why This Works
Recursion lets us dig into every nested dictionary without needing to know the structure in advance. Each time we encounter a nested dict, we repeat the key-checking process on it, ensuring no instance of the target key is missed—regardless of how deep it’s buried in the hierarchy.
内容的提问来源于stack exchange,提问作者Luke101

