使用要设置的字符串元组(键、值)更新Python字典失败

使用要设置的字符串元组(键、值)更新Python字典失败,python,dictionary,grammar,iterable,Python,Dictionary,Grammar,Iterable,说 使用其他键/值对更新字典,覆盖现有键。无返回 update接受另一个dictionary对象或键/值对的iterable作为元组或长度为2的其他iterable。如果指定了关键字参数,则使用这些键/值对更新字典:d.updater=1,blue=2 但是 那么为什么Python显然试图使用元组的第一个字符串呢?直接的解决方案是:唯一的参数other是可选的,是元组的iterable或长度为2的其他iterable 无参数它是可选的,当您不需要它时:-: >>> d = {}

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

update接受另一个dictionary对象或键/值对的iterable作为元组或长度为2的其他iterable。如果指定了关键字参数,则使用这些键/值对更新字典:d.updater=1,blue=2

但是


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

直接的解决方案是:唯一的参数other是可选的,是元组的iterable或长度为2的其他iterable

无参数它是可选的,当您不需要它时:-:

>>> d = {}
>>> d.update()
>>> d
{}
带元组的列表不要将其与包含可选参数的方括号混淆!:

>>> d = {}
>>> d.update([("key", "value")])
>>> d
{'key': 'value'}
根据,元组作为所有序列类型也是一个iterable,但是这失败了:

>>> 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
所以这是可行的:

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

由于上述语法歧义,逗号是函数参数分隔符。

直接的解决方案是:唯一的参数other是可选的,由元组或其他长度为2的iterable组成

无参数它是可选的,当您不需要它时:-:

>>> d = {}
>>> d.update()
>>> d
{}
带元组的列表不要将其与包含可选参数的方括号混淆!:

>>> d = {}
>>> d.update([("key", "value")])
>>> d
{'key': 'value'}
根据,元组作为所有序列类型也是一个iterable,但是这失败了:

>>> 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
所以这是可行的:

>>> 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
由于上述语法歧义,逗号是函数参数分隔符