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

标签 python dictionary grammar iterable

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

最佳答案

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

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

相关文章:

python - Pandas 根据最接近的匹配合并数据帧

python - 在python中按给定顺序排列列表以转储到json中

c++ - 使用类方法插入 std::map

c++ - 如何解决不匹配的替代解析器及其属性

internationalization - 自然语言语法和用户输入的名称

键上 dict 正则表达式的 Python dict

python - 类没有指定表或表名,也没有从现有的表映射类继承

Swift 字典数组

javascript - 隐藏标记 - Mapbox

prolog - 是否有序言语言语法/规范?