嵌套字典的值修改:为指定键添加对应值
How to Update Specific Keys in a Nested Dictionary with a Flat Key-Value Mapping
Got it, let's walk through how to solve this. You've got a deeply nested dictionary, and you want to update specific keys (like item1 and item2) with values from a flat values_to_add dict. Here's a straightforward recursive approach that works regardless of how deep your nested structure is:
Solution Code
# Your original nested dictionary original_dict = { "Title": { "Label-1": { "sublabel-1": {"item1": {}, "item2": {}}, "sublabel-2": {"item3": {}, "item4": {}, "item5": {}} }, "Label-2": { "sublabel-1": {"item6": {}, "item7": {}, "item8": {}} } } } # The key-value pairs you want to add values_to_add = {"item1": "a", "item2": "b"} def update_nested_dict(nested_dict, updates): # Loop through each key in the current dictionary level for key, value in nested_dict.items(): # If this key is in our updates list, replace its value if key in updates: nested_dict[key] = updates[key] # If the value is another dictionary, dig deeper recursively elif isinstance(value, dict): update_nested_dict(value, updates) # Run the update function update_nested_dict(original_dict, values_to_add) # Verify the changes print(original_dict["Title"]["Label-1"]["sublabel-1"]["item1"]) # Output: 'a' print(original_dict["Title"]["Label-1"]["sublabel-1"]["item2"]) # Output: 'b'
How This Works
- Recursive Traversal: The function
update_nested_dictgoes through every level of your nested dictionary. For each key, it checks if the key exists invalues_to_add. If it does, it replaces the existing value (in your case, the empty{}) with the corresponding value fromvalues_to_add. - Handling Nested Levels: When the function encounters a value that's another dictionary, it calls itself to traverse that sub-dictionary—this ensures we don't miss any keys buried deep in the structure.
Note
If your nested dictionary has duplicate key names across different levels (e.g., another item1 in sublabel-2), this function will update all instances of that key. If you only want to update keys at a specific path, you'd need to modify the function to target that exact path instead of traversing everything.
内容的提问来源于stack exchange,提问作者UserA
相关产品推荐
相关产品推荐

