用要设置的字符串元组(key,value)更新Python字典失败

2024-06-02 07:08:01 发布

您现在位置:Python中文网/ 问答频道 /正文

^{}

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


Tags: orofthekeyfromdictionaryisvalue
1条回答
网友
1楼 · 发布于 2024-06-02 07:08:01

直接的解决方案是:唯一的参数other可选的和元组的iterable(或者其他长度为2的iterable)。在

无参数(这是可选的,因为当您不需要它时:-):

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

用元组列出(不要把它与括在可选参数中的方括号混淆!)公司名称:

^{pr2}$

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

^{3}$

Python documentation on ^{}再次解开了这个谜团:

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)根本不是元组,但{}是:

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

因为是语法分隔符。在

相关问题 更多 >