如何制作一个字典,该字典返回字典中缺少的键的键而不是引发 KeyError?

新手上路,请多包涵

我想创建一个 python 字典,它返回字典中缺少的键的键值。

使用示例:

 dic = smart_dict()
dic['a'] = 'one a'
print(dic['a'])
# >>> one a
print(dic['b'])
# >>> b

原文由 sorin 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 437
2 个回答

dict 有一个 __missing__ 挂钩:

 class smart_dict(dict):
    def __missing__(self, key):
        return key

可以将其简化为(因为 self 从未使用过):

 class smart_dict(dict):
    @staticmethod
    def __missing__(key):
        return key

原文由 Jochen Ritzel 发布,翻译遵循 CC BY-SA 4.0 许可协议

你为什么不直接使用

dic.get('b', 'b')

当然,您可以子类 dict 正如其他人指出的那样,但我发现每隔一段时间提醒自己 get 可以有一个默认值很方便!

如果你想试试 defaultdict ,试试这个:

 dic = defaultdict()
dic.__missing__ = lambda key: key
dic['b'] # should set dic['b'] to 'b' and return 'b'

除了……好吧: AttributeError: ^collections.defaultdict^object attribute '__missing__' is read-only ,所以你必须继承:

 from collections import defaultdict
class KeyDict(defaultdict):
    def __missing__(self, key):
        return key

d = KeyDict()
print d['b'] #prints 'b'
print d.keys() #prints []

原文由 Daren Thomas 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题