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

如何实现支持键级默认值的Python defaultdict?

实现带键提示的自定义默认字典

直接用defaultdict的default_factory做不到,因为这个工厂函数是无参的,传带参数的lambda会因调用时没传参触发TypeError。要实现访问不存在的键时返回包含该键的提示,有两种简单方案:

方案一:继承defaultdict重写__missing__方法

这是最贴合需求的方式,既保留defaultdict的原有特性,又能自定义缺失键的返回值:

from collections import defaultdict

class ConfigDict(defaultdict):
    def __missing__(self, key):
        return f'You can set {key} to inject configuration here'

# 测试使用
cfg = ConfigDict()
print(cfg['db_host'])  # 输出: You can set db_host to inject configuration here
print(cfg['api_key'])   # 输出: You can set api_key to inject configuration here

__missing__是字典类的特殊方法,当访问不存在的键时会自动被调用,这里直接利用传入的key生成提示字符串即可。

方案二:自定义普通字典类

如果不想依赖defaultdict,也可以直接写一个普通字典的子类,重写__getitem__方法:

class ConfigDict(dict):
    def __getitem__(self, key):
        try:
            return super().__getitem__(key)
        except KeyError:
            return f'You can set {key} to inject configuration here'

# 测试效果和方案一完全一致
cfg = ConfigDict()
print(cfg['redis_port'])  # 输出: You can set redis_port to inject configuration here

两种方案都能满足需求,方案一更推荐,因为defaultdict本身就是为默认值场景设计的,代码更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 14:34:52