Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lambda function returning the key value for use in defaultdict

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 ?

like image 425
sixdiamants Avatar asked Dec 02 '16 12:12

sixdiamants


1 Answers

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'
like image 101
jsbueno Avatar answered Nov 26 '22 08:11

jsbueno