Python中嵌套字典取值的正确方法及更优实践探讨
Python提取嵌套字典值的更优实践方案
先看你给出的嵌套字典示例代码:
nested_dict = {"fruit": {"apple":{"status": "new", "sold": True}, "banana": 10, "watermelon": 30}, "meat": {"red": 39, "white": 13}} res = nested_dict.get("fruit", {}).get("apple", {}).get("status") if res: print(f"{res = }")
这种链式get的写法虽然安全,但路径较长时会显得繁琐,下面是几种更优的实践方案:
1. 用functools.reduce简化链式调用
借助标准库的reduce,可以把路径抽成列表,简化重复的get调用:
from functools import reduce def get_nested_value(data, path, default=None): try: return reduce(lambda d, key: d[key], path, data) except (KeyError, TypeError): return default # 使用示例 res = get_nested_value(nested_dict, ["fruit", "apple", "status"]) print(f"{res = }") # res = 'new' # 路径不存在时返回默认值 res = get_nested_value(nested_dict, ["fruit", "orange", "status"], default="unknown") print(f"{res = }") # res = 'unknown'
优点:路径以列表形式传递,可读性更强,函数可复用;缺点:需要封装异常处理,但封装后无需重复编写。
2. 自定义递归函数处理任意深度
如果嵌套结构的深度不确定,递归函数能灵活适配:
def get_nested_recursive(data, keys, default=None): if not keys or data is None: return data if data is not None else default key = keys[0] if isinstance(data, dict) and key in data: return get_nested_recursive(data[key], keys[1:], default) else: return default # 使用示例 res = get_nested_recursive(nested_dict, ["fruit", "apple", "sold"]) print(f"{res = }") # res = True
优点:支持动态深度的嵌套结构,能处理中途非字典的情况;缺点:极端深度可能触发递归限制,但日常场景基本无影响。
3. 直接索引+异常捕获(适合确定路径存在的场景)
如果能确定目标路径一定存在,直接用索引的性能更好,搭配try-except处理意外情况:
try: res = nested_dict["fruit"]["apple"]["status"] print(f"{res = }") except (KeyError, TypeError): res = "unknown" print(f"{res = }")
优点:性能最优,代码直观;缺点:路径不存在时会抛出异常,必须用try-except兜底,适合路径大概率存在的场景。
4. Python 3.10+ 用match-case模式匹配
如果你的Python版本是3.10及以上,match-case可以更清晰地匹配固定嵌套结构:
match nested_dict: case {"fruit": {"apple": {"status": s}}}: print(f"{s = }") case _: print("路径不存在")
优点:语法简洁直观,结构一目了然;缺点:依赖Python版本,不适用于动态变化的路径。
5. 第三方库(可选)
如果项目允许引入第三方库,glom这类工具专门处理嵌套数据,功能强大:
from glom import glom, Coalesce res = glom(nested_dict, Coalesce("fruit.apple.status", default="unknown")) print(f"{res = }")
优点:支持复杂路径表达式、默认值设置甚至数据转换;缺点:需要额外安装库,小型项目可能没必要。
内容的提问来源于stack exchange,提问作者tung
相关产品推荐
相关产品推荐

