Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.
update() accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs: d.update(red=1, blue=2).
但是
>>> {}.update( ("key", "value") )
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 3; 2 is required
那么为什么 Python 显然会尝试使用元组的第一个字符串?
最佳答案
参数必须是元组的可迭代对象(或其他长度为二的可迭代对象),例如一个列表
>>> d = {}
>>> d.update([("key", "value")])
>>> d
{'key': 'value'}
或者一个元组,但是这失败了:
>>> d = {}
>>> d.update((("key", "value")))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 3; 2 is required
Python documentation on tuple
再次解开这个谜团:
Note that it is actually the comma which makes a tuple, not the parentheses. The parentheses are optional, except in the empty tuple case, or when they are needed to avoid syntactic ambiguity.
即(None)
根本不是一个元组,但是 (None,)
是:
>>> type( (None,) )
<class 'tuple'>
所以这是可行的:
>>> d = {}
>>> d.update((("key", "value"),))
>>> d
{'key': 'value'}
>>>
你不能省略括号,因为
>>> d = {}
>>> d.update(("key", "value"),)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 3; 2 is required
那就是语法歧义(逗号是函数参数分隔符)。
关于python - 使用字符串元组更新 Python 字典以设置(键,值)失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43852535/