python – 字典不会以字符串作为键更新

我正在尝试使用返回元组的函数更新字典,其中第一个元素是字符串.

>>> def t():
...     return 'ABC', 123

然而,dict.update功能并不十分喜欢它.

>>> d = {}
>>> d.update(t())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 3; 2 is required

我也可以尝试字典理解并获得相同的意外结果.

>>> d.update({k: v for k, v in t()})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <dictcomp>
ValueError: too many values to unpack (expected 2)

唯一可行的方法是先保存返回值.

>>> x = t()
>>> d.update({x[0]: x[1]})
>>> d
{'ABC': 123}

怎么解释这个?

最佳答案 从
docs

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

例如:

In [1]: d = {}

In [2]: def t(): return [('ABC', '123')]

In [3]: d.update(t())

In [4]: d
Out[4]: {'ABC': '123'}

In [5]: d2 = {}

In [6]: def t2(): return {'ABC': '123'}

In [7]: d2.update(t2())

In [8]: d2
Out[8]: {'ABC': '123'}
点赞