python身份字典 [英] python identity dictionary

查看:60
本文介绍了python身份字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
如何制作一个python字典,返回字典中缺少的键的键,而不是引发KeyError?

Possible Duplicate:
How to make a python dictionary that returns key for keys missing from the dictionary instead of raising KeyError?

我需要类似defaultdict的东西.但是,对于字典中没有的任何键,它都应返回键本身.

I need something like a defaultdict. However, for any key that isn't in the dictionary, it should return the key itself.

做到这一点的最佳方法是什么?

What is the best way to do that?

推荐答案

使用神奇的__missing__方法:

>>> class KeyDict(dict):
...     def __missing__(self, key):
...             return key
... 
>>> x = KeyDict()
>>> x[2]
2
>>> x[2]=0
>>> x[2]
0
>>> 

这篇关于python身份字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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