Why is lambda allowed as a key in a dict?

David Stanek dstanek at dstanek.com
Mon Mar 9 23:21:39 EDT 2009


On Mon, Mar 9, 2009 at 11:07 PM, Daniel Fetchinson
<fetchinson at googlemail.com> wrote:
> Python 2.5.1 (r251:54863, Oct 30 2007, 13:45:26)
> [GCC 4.1.2 20070925 (Red Hat 4.1.2-33)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> x = { }
>>>> x[lambda arg: arg] = 5
>>>> x[lambda arg: arg]
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
> KeyError: <function <lambda> at 0x2aaaaabaab18>
>
> Is this a case of "we are all adults here"? I should only blame myself
> for making an unnamed function a dictionary key or should it be
> forbidden? Or am I missing something completely?
>

Each time you are using lambda to create a new anonymous function
object. It is not giving you the same object. If you save the
reference to the lambda you can easily get it back:

>>> l = lambda arg: arg
>>>
>>> d= {}
>>> d[l] = 5
>>> d[l]
5

-- 
David
blog: http://www.traceback.org
twitter: http://twitter.com/dstanek



More information about the Python-list mailing list