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

标签 python dictionary

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

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

相关文章:

c - 结构 |结构/union 的不完整类型错误

python - Django Rest Framework 嵌套关系

python - 如何将关联的相邻 Pandas 数据框数据导出到字典中?

swift - 字典的扩展 where <String, AnyObject>

python - 在 Selenium 中编辑文本字段

pandas - 将具有 nan 值的 str 类型字典转换为 dict 类型对象

json - Swift:将Optional<AnyObject> 转换为TimeInterval 错误

python - numpy 库的“包含”?

python - 如何在 python 中将某些行存储在变量中?

python - 如何按列表中的多个项目从最高到最低对列表进行排序?