Possible Duplicate:
How to make a python dictionary that returns key for keys missing from the dictionary instead of raising KeyError?
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?
Use the magic __missing__
method:
>>> class KeyDict(dict):
... def __missing__(self, key):
... return key
...
>>> x = KeyDict()
>>> x[2]
2
>>> x[2]=0
>>> x[2]
0
>>>
you mean something like the following?
value = dictionary.get(key, key)
class Dict(dict):
def __getitem__(self, key):
try:
return super(Dict, self).__getitem__(key)
except KeyError:
return key
>>> a = Dict()
>>> a[1]
1
>>> a[1] = 'foo'
>>> a[1]
foo
This works if you have to support Python < 2.5 (which added the __missing__
method mentioned by @katrielalex).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With