Why is lambda allowed as a key in a dict?

Ryan Kelly ryan at rfk.id.au
Mon Mar 9 23:17:48 EDT 2009


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

I think the point is that function objects compare by object identity,
so the two lambdas you use above are not equal even though they have the
same code.  Consider:

>>> a = lambda arg: arg
>>> x = {}
>>> x[a] = 5
>>> x[a]
5
>>> x[lambda arg:arg]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: <function <lambda> at 0xa06602c>
>>> 


  Cheers,

     Ryan

-- 
Ryan Kelly
http://www.rfk.id.au  |  This message is digitally signed. Please visit
ryan at rfk.id.au        |  http://www.rfk.id.au/ramblings/gpg/ for details

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 204 bytes
Desc: This is a digitally signed message part
URL: <http://mail.python.org/pipermail/python-list/attachments/20090310/66729c3b/attachment-0001.sig>


More information about the Python-list mailing list