7

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?

Community
  • 1
  • 1
max
  • 49,282
  • 56
  • 208
  • 355
  • 2
    Terminology nitpick: An identity dict is usually taken to be a dictionary that uses object identity (`id`) for keys instead of hashes. –  Dec 13 '11 at 20:13
  • Ahh, I didn't find the other question. Thanks for pointing it out. Is there a way to consolidate the two questions? The accepted answer to the other question is shown to be wrong though, and the OP didn't bother to change his acceptance. – max Dec 14 '11 at 00:54
  • @max: there's a Stack Overflow process for handling duplicate questions. It will all get taken care of =) – Katriel Dec 14 '11 at 01:53

3 Answers3

15

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
>>> 
Katriel
  • 120,462
  • 19
  • 136
  • 170
10

you mean something like the following?

value = dictionary.get(key, key)
moooeeeep
  • 31,622
  • 22
  • 98
  • 187
  • +1 one-line solution, no need for classes or overwriting – juliomalegria Dec 13 '11 at 20:25
  • 1
    The downside to the `get` approach is that you are replicating the "return key when not found" rule all over your code. If this is a rule for all accesses, then it is best to implement that functionality _once_ in the container itself (see @katrielalex's `__missing__` answer) rather than *k* times throughout the code. – Nathan Dec 13 '11 at 20:39
  • Unfortunately, I neglected to specify that it has to be a dictionary (it's passed to functions that expect to call dictionary methods). – max Dec 14 '11 at 00:56
2
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).

Nathan
  • 4,777
  • 1
  • 28
  • 35