dictionary-question
wl
wl at flexis.de
Wed Nov 21 11:14:03 EST 2001
Hello,
Bas van Gils wrote:
> 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
> workaround?
Better sollution:
foo["bar"] = foo.get("bar",0) +1
That works as expected.
foo.get("bar",0) += 1 won't work because you try
to assign something to a function.
Thist is the same as foo.get("bar",0) = foo.get("bar",0) + 1
( or same with __add__( ... ) )
The function is not evaluted, all is parsed from right to left.
But if it goes the other way it makes no sense to add 1 to the
integer value 0. ( foo.get("bar",0) returns 0 if bar is not present
into foo, not foo["bar"] with value 0 ).
bye by Wolfgang
More information about the Python-list
mailing list