如何制作一个字典,为字典中缺少的键返回键,而不是引发KeyError? [英] How to make a dictionary that returns key for keys missing from the dictionary instead of raising KeyError?

查看:34
本文介绍了如何制作一个字典,为字典中缺少的键返回键,而不是引发KeyError?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要创建一个python字典,该字典向我返回字典中缺少的键的键值。

使用示例:

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

推荐答案

dict有一个__missing__挂钩:

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

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

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

这篇关于如何制作一个字典,为字典中缺少的键返回键,而不是引发KeyError?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆