Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python identity dictionary [duplicate]

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?

like image 474
max Avatar asked Dec 13 '11 20:12

max


3 Answers

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
>>> 
like image 70
Katriel Avatar answered Sep 27 '22 23:09

Katriel


you mean something like the following?

value = dictionary.get(key, key)
like image 23
moooeeeep Avatar answered Sep 28 '22 00:09

moooeeeep


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).

like image 21
Nathan Avatar answered Sep 28 '22 00:09

Nathan