摘要:我们都知道 dict.get(key, default) 可以避免 KeyError,collections.defaultdict 可以自动为缺失键生成默认值。
分享兴趣,传播快乐,
增长见闻,留下美好!
亲爱的您,这里是LearningYard新学苑。
今天小编为大家带来文章
“刘心向学(40):__missing__:掌控字典的“缺省响应””
Share interest, spread happiness,
Increase knowledge, leave a beautiful!
Dear, this is LearningYard Academy.
Today, the editor brings you an article.
“Liu Xinxiangxue (40): __missing__: Mastering the "Default Response" of Dictionaries”
Welcome to your visit.
我们都知道 dict.get(key, default) 可以避免 KeyError,collections.defaultdict 可以自动为缺失键生成默认值。
We all know that can avoid KeyError, and can automatically generate default values for missing keys.
However, both have limitations:
get
每次都要写默认值,不够优雅。
get
requires writing a default value every time, which is not elegant.
defaultdict
的默认工厂是固定的,无法根据键动态决定。
defaultdict
has a fixed default factory and cannot dynamically decide based on the key.
__missing__(self, key) 是 dict 子类中的一个特殊方法,它在以下情况下被调用:
__missing__(self, key) is a special method in subclasses of dict. It is called under the following condition:
当通过 访问一个不存在的键时,__getitem__ 方法会先查找键,若未找到,则调用 self.__missing__(key)。
When accessing a non-existent key via , the __getitem__ method first looks up the key; if not found, it calls self.__missing__(key).
只对 dict 的子类有效。
only works in subclasses of dict.
它不会被 get、in、keys 等方法调用。
It is not called by methods like get, in, or keys.
它的返回值将作为 表达式的结果。
Its return value becomes the result of the expression.
Python深色版本classSafeDict(dict):def__missing__(self, key):returnf"Key '{key}' not found"d = SafeDict({"a": 1, "b": 2})print(d["a"]) # 输出: 1print(d["c"]) # 输出: Key 'c' not found(无 KeyError)Python深色版本classDefaultDict(dict):def__missing__(self, key):return0# 所有缺失键默认为 0scores = DefaultDict({"math": 90, "english": 85})print(scores["math"]) # 90print(scores["science"]) # 0(自动补全)Python深色版本classConfig(dict):def__missing__(self, key):if key.startswith("user_"):returnf"default_{key.split('_', 1)[1]}"elif key.startswith("timeout_"):return30# 默认超时 30 秒raise KeyError(key)config = Configprint(config["user_name"]) # default_nameprint(config["timeout_api"]) # 30# print(config["invalid"]) # KeyErrorAutomatically cache results when accessing databases or APIs:
Python深色版本classCachedDict(dict):def__init__(self, fetch_func):super.__init__ self.fetch_func = fetch_func # 获取数据的函数def__missing__(self, key):print(f"Fetching data for key: {key}") value = self.fetch_func(key) self[key] = value # 缓存结果return value# 模拟数据库查询defload_user(user_id):return {"id": user_id, "name": f"User{user_id}"}cache = CachedDict(load_user)print(cache[1]) # Fetching... {'id': 1, 'name': 'User1'}print(cache[1]) # 直接从字典返回,不打印 FetchingPython深色版本classCaseInsensitiveDict(dict):def__init__(self, *args, **kwargs):super.__init__ self.update(*args, **kwargs)def__missing__(self, key):# 尝试小写版本ifisinstance(key, str): lower_key = key.lowerfor k, v in self.items:ifisinstance(k, str) and k.lower == lower_key:return vraise KeyError(key)cid = CaseInsensitiveDict({"Name": "Alice", "AGE": 30})print(cid["name"]) # Alice(自动匹配 "Name")print(cid["AGE"]) # 30Python深色版本def__missing__(self, key):# 错误:不返回也不抛出 → 返回 None# 正确做法:if key in self.fallback:return self.fallback[key]else:raise KeyError(key) # 显式抛出Python深色版本def__missing__(self, key):return self[key] # ❌ 无限递归!self[key] 会再次触发 __missing____missing__ 是一个低调但强大的魔法方法。它让你能够:
__missing__ is a low-profile but powerful magic method. It enables you to:
拦截“键不存在”的异常
Intercept "key not found" exceptions
返回默认值、动态生成数据、实现缓存
Return default values, dynamically generate data, or implement caching
构建更智能、更符合业务逻辑的字典类型
Build smarter, more business-logic-aware dictionary types
虽然 defaultdict 和 get 已能满足大多数场景,但当你需要根据键名、上下文或外部资源动态决定缺失值时,__missing__ 就是那个“瑞士军刀”般的解决方案。
While defaultdict and get cover most common use cases, __missing__ becomes the "Swiss Army knife" solution when you need to dynamically decide missing values based on key names, context, or external resources.
掌握它,你的字典将不再“沉默地报错”,而是“智慧地响应”。
Master it, and your dictionaries will no longer "silently error" — they will "respond intelligently".
今天的分享就到这里了。
如果您对文章有独特的想法,
欢迎给我们留言,
让我们相约明天。
祝您今天过得开心快乐!
That's all for today's sharing.
If you have a unique idea about the article,
please leave us a message,
and let us meet tomorrow.
I wish you a nice day!
参考资料:通义千问
参考文献:Beazley, D., & Jones, B. K. (2019). Python Cookbook (3rd ed.). O'Reilly Media.
Hettinger, R. (2019). Transforming Code into Beautiful, Idiomatic Python. PyCon US.
本文由LearningYard新学苑整理发出,如有侵权请在后台留言沟通!
LearningYard新学苑
文字:song
排版:song
审核|hzy
来源:LearningYard学苑