You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

嵌套字典的值修改:为指定键添加对应值

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_dict goes through every level of your nested dictionary. For each key, it checks if the key exists in values_to_add. If it does, it replaces the existing value (in your case, the empty {}) with the corresponding value from values_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:36:22