Link to home
Start Free TrialLog in
Avatar of BerkeleyJeff
BerkeleyJeff

asked on

Using setdefault to update that value of an int

I've recently been introducted to the setdefault function, and understand it can be used in the following way to update a dict's value, when that value is an array:

myDict.setdefault(myKey, []).append(myValue)

But how can I use setdefault to update the value of a dict, when that value is an int? For instance, the following statement gives me an error mesage:

myDict.setdefault(myKey, 0) += 1


Thanks!
ASKER CERTIFIED SOLUTION
Avatar of RichieHindle
RichieHindle

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of BerkeleyJeff
BerkeleyJeff

ASKER

It's too bad Python doesn't have a builtin function for that. It's such a common task, I would think that would have included it.

Is there a mutable int type, like what "Integer" is to "int" in Java? Maybe I could halve the number of dict accesses that way.
No, there's no mutable integer type.  You could write one, but it wouldn't make any appreciable difference - rather than two dictionary accesses, you'd have one dictionary access plus an object attribute access (which is a dictionary access under the hood anyway).
Thank you.