How to update dictionary from a tuple (or list of 2)

一世执手 提交于 2021-01-03 05:31:11

问题


I thought it would be possible to update an existing dictionary as follows:

nameValuePair = 'myKey=myValue'
d.update(nameValuePair.split('='))

However I get this error:

Traceback (most recent call last):
  File "<pyshell#98>", line 1, in <module>
    d2.update(item.split('='))
ValueError: dictionary update sequence element #0 has length 1; 2 is required

I looked at some other StackOverflow questions/answers on this topic, which made me think this was possible. I must be missing something basic...


回答1:


The error message already gives you a hint: Each item in the sequence you pass must have a length of 2, meaning it has to consist of a key and a value.

Therefore you have to pass a tuple (list, sequence,...) of 2-tuples (-lists, -sequences,...):

// the value passed will be ((myKey, myValue), )
d.update((nameValuePair.split('='), ))
//       ^                        ^ ^
// creates a tuple of 1 element

Alternatively you could do:

key, value = nameValuePair.split('=')
d[key] = value


来源:https://stackoverflow.com/questions/11746668/how-to-update-dictionary-from-a-tuple-or-list-of-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!