我正在尝试使用返回第一个元素是字符串的元组的函数来更新字典。
>>> 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'}
关于python - 字典不会以字符串作为键更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42032093/