Python identification dictionary

Possible duplicate:
How to make a python dictionary that returns a key for keys that are not in the dictionary, instead of raising a KeyError?

I need something like defaultdict . However, for any key that is not in the dictionary, it must return the key itself.

What is the best way to do this?

+4
source share
3 answers

Use the __missing__ magic method:

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

do you mean something like the following?

 value = dictionary.get(key, key) 
+8
source
 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 need to support Python <2.5 (which added the __missing__ method mentioned by @katrielalex).

+1
source

Source: https://habr.com/ru/post/1386182/


All Articles