Question

I am a noob in Python and I am getting stacked in something that I am sure it is easy but I just cannot figure it out.

I have a dictionary that has a string as key and a list as value:

d = {'ABCDEFG':[0,1,2,3]}

>>> d
{'ABCDEFG': [0, 1, 2, 3]}

I can assign new values to the item already in the list:

d['ABCDEFG'][0] = 1

>>> d
{'ABCDEFG': [1, 1, 2, 3]}

But here is the problem: How can I add new items into the list (expand the list) so that it results:

>>> d
{'ABCDEFG': [1, 1, 2, 3, 4]}

and what if I would like to get a list of list inside the dictionary?

>>> d
{'ABCDEFG': [1, 1, 2, 3, [4, 5]]}

In a normal list I would use .append() but if I try to append something to the list inside the dictionary I get SyntaxError or AttributeError, for sure I am doing something wrong... What is the correct way to do it?

Thanks!

Was it helpful?

Solution

It was some unspecified python problem... I have solved by changing the interpreter.

now it works!

d['ABCDEFG'].append(4)

>>> d
{'ABCDEFG': [0, 1, 2, 3, 4]}

and

d['ABCDEFG'].append([5,6])

>>> d
{'ABCDEFG': [0, 1, 2, 3, 4, [5, 6]]}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top