How to add new value in existing key in dictionary(without losing the previous values)?

Viewed 129

I have this dictionary filled with keys (each key is a tuple) and value None for each key. I want to add values (one at a time) within a for loop to the keys, without overwriting values

This code has an error message " AttributeError: 'NoneType' object has no attribute 'append' "

dictionary1={}
dictionary1.update( {(0,0) : None} )

listOfTuples=[(0,0),(1,0),(9,0)]
for x in range(3):
    dictionary1[(0,0)].append(listOfTuples(x))

The result i want is the dictionary1 to be like:

{ (0,0) : [(0,0),(1,0),(9,0)] }

But i want it to be filled in the for loop one tuple at a time

2 Answers

So in order for this to work the way you want, you'll have to replace the None with an empty List [] because right now you are trying to append (0,0) to None, hence the error.

dictionary1={}
dictionary1.update( {(0,0) : []} )

As mentioned by C. Lewis, you need to replace None to an empty list in the dictionary update.

Also, listOfTuples is a list, therefore you need to access its element using the syntax listOfTuples[index] instead of listOfTuples(index).

The following code achieves the expected results:

dictionary1={}
dictionary1.update( {(0,0) : []} )

print(dictionary1.keys())
listOfTuples=[(0,0),(1,0),(9,0)]
for x in range(3):
    dictionary1[(0,0)].append(listOfTuples[x])

print(dictionary1) # {(0, 0): [(0, 0), (1, 0), (9, 0)]}
Related