lambda function returning the key value for use in defaultdict

2024/10/3 14:20:29

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 ?

Answer

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'
https://en.xdnf.cn/q/70718.html

Related Q&A

Calling Matlab function from python

I have one project in which I have one one matlab code which I have to run tho Django. I tried installing Mlabwrap ..But it gives me following error.Traceback (most recent call last): File "<st…

Suds ignoring proxy setting

Im trying to use the salesforce-python-toolkit to make web services calls to the Salesforce API, however Im having trouble getting the client to go through a proxy. Since the toolkit is based on top of…

CSV to JSON script

I took this script from here: import csv from itertools import izip f = open( /django/sw2/wkw2/csvtest1.csv, r ) reader = csv.reader( f ) keys = ( "firm_url", "firm_name", "fir…

Accessing an ALREADY running process, with Python

Question: Is there a way, using Python, to access the stdout of a running process? This process has not been started by Python.Context: There is a program called mayabatch, that renders out images fro…

sum up two pandas dataframes with different indexes element by element

I have two pandas dataframes, say df1 and df2, of some size each but with different indexes and I would like to sum up the two dataframes element by element. I provide you an easy example to better und…

Urwid: make cursor invisible

Im using urwid, which is a Python "framework" for designing terminal user interfaces in ncurses. Theres one thing though that Im not able to do in urwid that was easy in curses - make the cur…

How do I use scipy.weave.inline together with external C libraries?

I am trying to understand weave.inline to wrap C code in my Python programs. The code below simply takes the Numpy array and multiplicates all of its elements by 2.inl.py import numpy import scipy.weav…

sqlalchemy multiple foreign keys to same table

I have a postgres database that looks something like this:Table "public.entities"Column | Type | Modifiers ---------------+---…

Django - Return a file from Root folder via a URL

I purchased a SSL cert online and now ind the mid of verifying my host. How it works is:It gives me a file I have to make that file accessible through a specific URL on my host. If the content of the f…

Flask deployement on lighttpd and raspberry pi

Im trying to deploy a hello flask app to a raspberry pi using lighttpd fastCGI.I followed the instructions on the http://flask.pocoo.org/docs/0.10/deploying/fastcgi/ to the best of my abilityHere is my…