简体   繁体   中英

update multi value dictionary in python

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...

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM