Dictionary assignment

John J. Lee jjl at pobox.com
Sat Aug 16 05:31:14 EDT 2003


Istvan Albert <ialbert at mailblocks.com> writes:

> 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.

Maybe it's surprising to some Perl users.  Personally, it doesn't
surprise me (and I did come from Perl) that if you didn't add a key 2
to the dictionary a, it complains when you look up 2 in that dict.


> 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".

That's precisely what *does* happen, if you replace the first
'assignment to' in that sentence with 'item lookup' or 'indexing'.
The key 2 is not automagically created when it's found to be missing.
Perhaps you wanted:

a.setdefault(2, {})[3] = 4

?

How would it know what to index-assign to a[2] otherwise?  A dict?  A
list?  Something else?


> The error message one expects is that a[2]
> does not support assigment.

a[2] doesn't exist in your example above.


John




More information about the Python-list mailing list