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

han*_*dle 3 python grammar dictionary iterable

dict.update([other])

使用其他的键/值对更新字典,覆盖现有的键。返回

update() 接受另一个字典对象或键/值对的可迭代对象(作为元组或长度为 2 的其他可迭代对象)。如果指定了关键字参数,则字典将使用这些键/值对进行更新: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
Run Code Online (Sandbox Code Playgroud)

那么为什么 Python 显然会尝试使用元组的第一个字符串呢?

han*_*dle 6

参数必须是元组的可迭代对象(或长度为 2 的其他可迭代对象),例如列表

>>> d = {}
>>> d.update([("key", "value")])
>>> d
{'key': 'value'}
Run Code Online (Sandbox Code Playgroud)

或元组,但是这失败了:

>>> 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
Run Code Online (Sandbox Code Playgroud)

Python 文档tuple再次解开了这个谜团:

请注意,实际上是逗号构成了元组,而不是括号。括号是可选的,除非在空元组情况下,或者需要它们以避免语法歧义时。

Ie(None)根本不是一个元组,而是(None,)

>>> type( (None,) )
<class 'tuple'>
Run Code Online (Sandbox Code Playgroud)

所以这有效:

>>> d = {}
>>> d.update((("key", "value"),))
>>> d
{'key': 'value'}
>>>
Run Code Online (Sandbox Code Playgroud)

你不能省略括号,因为

>>> 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
Run Code Online (Sandbox Code Playgroud)

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