Overriding iadd for dictionary like objects

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Aug 29 09:10:11 CEST 2009

On Sat, 29 Aug 2009 01:23:59 -0400, Joshua Judson Rosen wrote:

> Robert Kern <robert.kern at gmail.com> writes:
>> On 2009-08-28 16:42 PM, Terry Reedy wrote:
>> > Carl Banks wrote:
>> >
>> > > I don't think it needs a syntax for that, but I'm not so sure a
>> > > method to modify a value in place with a single key lookup wouldn't
>> > > occasioanally be useful.
>> >
>> > Augmented assignment does that.
>> No, it uses one __getitem__ and one __setitem__ thus two key lookups.
> Apparently you're defining "key lookup" some other way than as `what
> __getitem__ does'.
> What exactly does "key lookup" mean to you?
> I've always understood it as `retrieving the value associated with a
> key', which obviously isn't required for assignment--otherwise it
> wouldn't be possible to add new keys to a mapping.

When you retrieve a value from a dictionary using __getitem__, e.g.:


the dict has to search the hash table for the record with key "K". This a 
key lookup.

(I use the term "search", but of course for hash tables this is usually 
very fast. For Python dicts, you can assume it will usually be a constant 
time, independent of the key or the size of the dict.)

When you store a value in a dictionary using __setitem__, e.g.:

dict["K"] = 42

the dict has to search the hash table for the correct place to store a 
record with key "K". It obviously can't place the record in some 
arbitrary place, it has to be in the correct place for future lookups to 
find it. This is also a key lookup.


More information about the Python-list mailing list