Why it doesn't work?

L

Lad

I have a list
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?

Thank you for reply
Rg,
L.
 
M

Martin P. Hellwig

Lad said:
I have a list
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?

Thank you for reply
Rg,
L.

Hi,

Perhaps what you try to do is something different than what I did here
but it works for me:
>>> D={'a':{'b':''}}
>>> D['a']['b']=2
>>> D
{'a': {'b': 2}}
 
T

Tomasz Lisowski

Lad said:
I have a list
L={}

This IS a dictionary, not a list.
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}}

You need to initialise L['a'] first, before referencing L['a']['b']

So, you need to call first:
L['a'] = {}

Then you can write:
L['a']['b'] = 2

Tomasz Lisowski
 
P

Peter Otten

Lad said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,276
Messages
2,571,384
Members
48,072
Latest member
FaustoBust

Latest Threads

Top