Dictionary assignment

Istvan Albert ialbert at mailblocks.com
Sat Aug 16 04:03:58 CEST 2003

Mark Daley wrote:

> format[self.formats.get()][key] = current[key]
> Now, all disgust from my example aside, shouldn't this line cause a new key
> (whatever self.formats get() produces) whose contents are an exact copy of
> current?

First you need to assure that format[self.formats.get()] contains 
another dictionary as a value. Here is an example:

>>>> a = {}
>>>> a[1] = {}
>>>> a[1][2] = 1

works as expected but

>>>> a[2][3] = 4

will fail with KeyError:2 because this construct attempts to fetch the
value corresponding to key 2 and then add to that dictionary the 3/4 
key/value pair.

It is indeed confusing, I never thought about it and caught me by 
surprise that it is KeyError:2 that is being thrown.

As one parses the expression from left to right it reads as if the 
assignment to key 2 comes first and only then does the assignment
to key 3 become "active". The error message one expects is that a[2]
does not support assigment.


More information about the Python-list mailing list