Why it doesn't work?

Peter Otten __peter__ at web.de
Mon Jan 9 10:33:13 CET 2006


Lad wrote:

> I have a list

A dictionary.

> L={}
> Now I can assign the value
> L['a']=1
> and I have
> L={'a': 1}
> 
> but I would like to have a dictionary like this
> L={'a': {'b':2}}
> 
> so I would expect I can do
> L['a']['b']=2
> 
> but it does not work. Why?

D["a"]["b"] = 2

translates to

D.__getitem__("a").__setitem__("b", 2)

When D doesn't already contain a key/value pair D = {"a": {}} the
__getitem__() call fails with a KeyError. If you don't know whether D
contains a key "a", use setdefault(key, value) which inserts the value only
if key is currently not in the dictionary. E. g.

>>> D = {}
>>> D.setdefault("a", {})["b"] = 42
>>> D.setdefault("a", {})["c"] = 24
>>> D
{'a': {'c': 24, 'b': 42}}

Peter




More information about the Python-list mailing list