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 ?
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'
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