gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:11:44 25 4
gpt4 key购买 nike

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com