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

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

问题描述

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

I want to create a python dictionary that returns me the key value for the keys are missing from the dictionary.

使用示例:

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

推荐答案

dicts 有一个 __missing__ 钩子:

dicts have a __missing__ hook for this:

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

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

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