【问题标题】:Update Python Dictionary with Tuple of Strings to set (key, value) fails使用要设置的字符串元组更新 Python 字典(键、值)失败
【发布时间】:2017-10-06 17:52:16
【问题描述】:

dict.update([other])

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

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

【问题讨论】:

    标签: python dictionary grammar iterable


    【解决方案1】:

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

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

    >>> 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 再次解开了这个谜团:

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

    (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
    

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

    【讨论】:

      猜你喜欢
      • 2017-10-01
      • 2021-06-16
      • 1970-01-01
      • 2019-03-17
      • 1970-01-01
      • 1970-01-01
      • 2013-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多