5

The function collections.defaultdict returns a default value that can be defined by a lambda function of my own making if the key is absent from my dictionary.

Now, I wish my defaultdict to return the unmodified key-value if that key is absent. Thus, I use a lambda identity function lambda x:x. I expect the defaultdict to return the key.

>>>translation=defaultdict(lambda x:x)
>>>translation['Haus']='maison'
>>>translation['computer']='ordinateur'
>>>translation['computer']
'ordinateur'

However, when I present my defaultdict with a hitherto absent key:

>>>translation['email']

I expect the defaultdict translation to return 'email'. However, python 2.7 says:

TypeError: <lambda>() takes exactly 1 argument (0 given)

Surely I'm doing something silly. But what ?

  • Possible duplicate of [How to make a python dictionary that returns key for keys missing from the dictionary instead of raising KeyError?](http://stackoverflow.com/questions/6229073/how-to-make-a-python-dictionary-that-returns-key-for-keys-missing-from-the-dicti) – Julien Marrec Dec 02 '16 at 12:08

1 Answers1

7

Unfortunately, the factory function for defining the missing key used in default dict takes no arguments - that is, unlike what would seem to be obvious, it is not passed the actual missing key.

Therefore, you can't know what the key that was tried is using this method.

An alternative is to subclass dict yourself (instead of using DefaultDict), and add a __missing__ method: it will be called whenever one tries to retrieve an unexisting key, and then you are free to return the received key:

In [86]: class MyDict(dict):
    ...:     __missing__ = lambda self, key: key
    ...:     

In [87]: m = MyDict()

In [88]: m["apples"]
Out[88]: 'apples'
jsbueno
  • 77,044
  • 9
  • 114
  • 168
  • Thanks; works a treat. Indeed somewhat counterintuitive that the lambda function isn't passed the key as input. – sixdiamants Dec 02 '16 at 12:58
  • This *is* awesome, but sadly highlights the uselessness of the standard `defaultdict` type. May Python 4.x purge us of these ills! – Cecil Curry May 20 '17 at 06:16