使用字符串元组更新 Python 字典以设置(键,值)失败

Update Python Dictionary with Tuple of Strings to set (key, value) fails

dict.update([other])

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 显然尝试使用元组的第一个字符串?

直接的解决方案是这样的:唯一的参数 otheroptional 和一个 iterable 元组(或其他可迭代对象)长度为二)。

没有参数(它是可选的,因为当你不需要它时:-):

>>> d = {}
>>> d.update()
>>> d
{}

用元组列出(不要将它与包含可选参数的方括号混淆!):

>>> d = {}
>>> d.update([("key", "value")])
>>> d
{'key': 'value'}

根据 Python glossary on iterables,元组(与所有序列类型一样)也是可迭代的,但是这失败了:

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

因为语法歧义(逗号是函数参数分隔符)。