dictionary-question

Mikael Olofsson mikael at isy.liu.se
Wed Nov 21 10:10:27 EST 2001


On 21-Nov-2001 Bas van Gils wrote:
 >  Hi,
 >  
 >  I just found some dictionary-behavior that I don't quite understand:
 >  
 >      Python 2.1.1 (#1, Nov  3 2001, 19:19:22)
 >      [GCC 2.95.4 20011006 (Debian prerelease)] on linux2
 >      Type "copyright", "credits" or "license" for more information.
 >      >>> foo = {}
 >      >>> type(foo.get("bar",0))
 >      <type 'int'>
 >      >>> foo.get("bar",0) += 1
 >      SyntaxError: can't assign to function call
 >  
 >  My current "workaround" is this:
 >  
 >      >>> if foo.has_key("bar"):
 >      ...     foo["bar"] += 1
 >      ... else:
 >      ...     foo["bar"] = 1
 >      ...
 >      >>> foo
 >      {'bar': 1}
 >  
 >  Now, can someone please explain why the 
 >  
 >      foo.get("bar",0) += 1
 >  
 >  won't work ... and what might be a better sollution then my current
 >  workaround?

I will not try to explain why. I guess it has to do with the fact that
the result of foo.get("bar",0) is never bound to any name. However, if
it was legal, it still would not do what you want it to do. In case it 
was legal, I suppose it would be equivalent to 

    temporaryVar = foo.get("bar",0)
    temporaryVar += 1
    del temporaryVar

and the entries of foo would not be affected, regardless of if foo['bar']
was defined before or not. 

Greetings
/Mikael

-----------------------------------------------------------------------
E-Mail:  Mikael Olofsson <mikael at isy.liu.se>
WWW:     http://www.dtr.isy.liu.se/dtr/staff/mikael               
Phone:   +46 - (0)13 - 28 1343
Telefax: +46 - (0)13 - 28 1339
Date:    21-Nov-2001
Time:    16:01:55

         /"\
         \ /     ASCII Ribbon Campaign
          X      Against HTML Mail
         / \

This message was sent by XF-Mail.
-----------------------------------------------------------------------
Linköpings kammarkör: www.kammarkoren.com




More information about the Python-list mailing list