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

如何将嵌套字典作为函数参数传递并实现遍历?

嵌套字典的递归遍历实现方案

没问题,嵌套字典的遍历用递归就能轻松搞定,咱们可以把通用的遍历逻辑和你自己的get_info处理函数拆分开,这样代码既灵活又容易维护。我给你写个具体的实现示例,一步一步来:

1. 先定义示例嵌套字典

假设你的嵌套字典长这样(你可以替换成自己的实际数据):

nested_dict = {
    "user": {
        "name": "Alice",
        "contact": {
            "email": "alice@example.com",
            "phone": {
                "home": "123-456-7890",
                "work": "098-765-4321"
            }
        }
    },
    "settings": {
        "theme": "dark",
        "notifications": True
    }
}

2. 编写你的get_info处理函数

这个函数负责你对每个键值对的具体业务操作,比如打印、存储、校验等,这里我先写个简单的打印示例:

def get_info(key, value):
    # 替换成你自己的业务逻辑即可
    print(f"处理键值对:Key = {key}, Value = {value}")

3. 实现递归遍历函数

这个函数是核心,它会自动遍历嵌套字典的每一层,遇到字典就继续深入,遇到普通值就调用你的get_info函数处理:

def traverse_nested_dict(data, process_func):
    # 遍历当前字典的所有键值对
    for key, value in data.items():
        if isinstance(value, dict):
            # 如果当前值是字典,递归调用自己继续遍历
            traverse_nested_dict(value, process_func)
        else:
            # 如果是普通值,调用传入的处理函数(也就是你的get_info)
            process_func(key, value)

4. 调用测试

现在只需要把嵌套字典和get_info函数传给遍历函数,就能完成全层级遍历了:

traverse_nested_dict(nested_dict, get_info)

运行后会输出:

处理键值对:Key = name, Value = Alice
处理键值对:Key = email, Value = alice@example.com
处理键值对:Key = home, Value = 123-456-7890
处理键值对:Key = work, Value = 098-765-4321
处理键值对:Key = theme, Value = dark
处理键值对:Key = notifications, Value = True

扩展:记录完整路径(可选)

如果你需要知道每个键的完整层级路径(比如user.contact.phone.home),可以修改遍历函数,把路径信息传递给get_info:

def traverse_nested_dict(data, process_func, current_path=""):
    for key, value in data.items():
        # 构建当前键的完整路径
        full_path = f"{current_path}.{key}" if current_path else key
        if isinstance(value, dict):
            traverse_nested_dict(value, process_func, full_path)
        else:
            process_func(full_path, value)

# 对应的修改get_info函数
def get_info(full_path, value):
    print(f"处理路径:{full_path}, Value = {value}")

调用后输出会变成:

处理路径:user.name, Value = Alice
处理路径:user.contact.email, Value = alice@example.com
处理路径:user.contact.phone.home, Value = 123-456-7890
处理路径:user.contact.phone.work, Value = 098-765-4321
处理路径:settings.theme, Value = dark
处理路径:settings.notifications, Value = True

这样不管你的嵌套字典有多深,都能完美遍历到每一个键值对,而且get_info函数可以完全专注于你自己的业务逻辑,不用关心遍历的细节。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:31:09