Lambda function returns key value for use in defaultdict

The collections.defaultdict function returns a default value, which can be determined using the lambda function of my own creation, if the key is not in my dictionary.

Now, I want my defaultdict to return the unchanged key value if this key is missing. Thus, I am using the lambda identity function lambda x: x. I expect 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 missing key:

>>>translation['email']

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

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

Of course I'm doing something stupid. But what?

+4
source share
1

, factory , , - , , , .

, , , .

dict ( DefaultDict) __missing__: , - ,

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

In [87]: m = MyDict()

In [88]: m["apples"]
Out[88]: 'apples'
+4

Source: https://habr.com/ru/post/1662628/


All Articles