update multi value dictionary in python

1.1k views Asked by At

I am trying to update a specific value in a two-dimensional dictionary where each set of key holds several values. My script is somewhat along these lines:

#!/usr/bin/python
mylist=['a', 2, 3, 4]
mydic = {}
mydic[mylist[0]] = mydic.get(mylist[0], {})
mydic[mylist[0]][mylist[1]] = mylist[2], mylist[3]
print mydic[mylist[0]][mylist[1]][0]

3

mydic[mylist[0]][mylist[1]][0] += 1

TypeError: 'tuple' object does not support item assignment

What goes wrong here and how should I instead update a specific value in a multi value dictionary? My actual list of key values are much longer than this example, so updating the entire key is not really a practical option...

1

There are 1 answers

0
fredtantini On BEST ANSWER

You got the error because you are trying to modify a tuple:

>>> a=(2,4)
>>> a[0]+=1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

As suggested by jonrsharpe's comment, if you want to be able to modify only some value, use a list instead of a tuple:

>>> mydic[mylist[0]][mylist[1]] = [mylist[2], mylist[3]]
>>> print mydic[mylist[0]][mylist[1]]
[3, 4]
>>> mydic[mylist[0]][mylist[1]][0] += 1
>>> print mydic[mylist[0]][mylist[1]]
[4, 4]