Werner Schiendl ws-news at gmx.at
Wed Nov 21 17:37:12 CET 2001


The get method of the dictonary returns the value stored at that position,
not a reference to the 'slot' in the dictionary.
Therefore, you cannot assign to the result of get.

The simplest that came to my mind is

>>> foo = {}
>>> foo["bar"]=foo.get("bar",0)+1
>>> foo
{'bar': 1}
>>> foo["bar"]=foo.get("bar",0)+1
>>> foo
{'bar': 2}


"Bas van Gils" <bas.vangils at home.nl> wrote in message
news:mailman.1006352607.21127.python-list at python.org...


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}

(this is just an demonstration of the behavior I don't get ... I want to
use it in a bigger script).

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

many thanks in advance



Bas van Gils <bas.vangils at home.nl>   -    http://members.home.nl/bas.vangils
Build a system that even a fool can use, and only a fool will want to use

More information about the Python-list mailing list