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

如何合并两个多层字典?Python新手技术问询

Multilevel Dictionary Merging in Python

Hey there! No worries at all—multilevel dictionary merging can feel tricky to track down when you're new to Python, so I’m glad you reached out. Let’s walk through how to handle this, using a common example that matches what you’re likely trying to do.

First, let’s assume your dictionaries look something like this (since you mentioned a multilevel structure):

Original Dictionaries:

dict1 = {
    "user": {
        "name": "Alice",
        "settings": {
            "theme": "light",
            "notifications": True
        }
    },
    "version": 1.0
}

dict2 = {
    "user": {
        "settings": {
            "theme": "dark",
            "language": "en"
        },
        "age": 30
    },
    "status": "active"
}

Desired Merged Dictionary (dict3):

dict3 = {
    "user": {
        "name": "Alice",
        "settings": {
            "theme": "dark",
            "notifications": True,
            "language": "en"
        },
        "age": 30
    },
    "version": 1.0,
    "status": "active"
}

Solution 1: Recursive Merge (Best for Multilevel Structures)

Python’s built-in dictionary methods (like update()) or the | operator (Python 3.9+) do shallow merges—meaning they’ll replace entire nested dictionaries instead of merging their contents. For true multilevel merging, we’ll write a simple recursive function:

def merge_multilevel_dicts(base, new):
    # Make a copy of the base dict to avoid modifying the original
    merged = base.copy()
    for key, value in new.items():
        # If both values are dictionaries, merge them recursively
        if isinstance(value, dict) and key in merged and isinstance(merged[key], dict):
            merged[key] = merge_multilevel_dicts(merged[key], value)
        # Otherwise, overwrite or add the new value
        else:
            merged[key] = value
    return merged

# Usage
dict3 = merge_multilevel_dicts(dict1, dict2)

How This Works:

  • We start by copying the base dictionary (dict1) so we don’t accidentally modify the original data.
  • For each key in the second dictionary (dict2):
    • If the value is a dictionary and the same key exists in the merged dict with another dictionary value, we recursively merge those nested dictionaries.
    • If it’s any other type (string, number, boolean, etc.), we just add/overwrite the key in the merged dict.

Solution 2: Shallow Merge (Only for Top-Level Keys)

If you only need to merge top-level keys and don’t care about preserving nested contents (they’ll be replaced entirely), you can use these simpler methods:

Python 3.9+

# Shallow merge: replaces entire nested dicts
dict3 = dict1 | dict2

Older Python Versions

dict3 = dict(dict1)
dict3.update(dict2)

Just remember—these won’t handle the multilevel merging you’re probably looking for, so stick with the recursive function for nested structures.

Let me know if your specific dictionary structure is different, and we can tweak this further!

内容的提问来源于stack exchange,提问作者michael0196

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:41:41