python身份字典 [英] python identity dictionary
本文介绍了python身份字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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屋!
查看全文