加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 11:57:41 所属栏目:Python 来源:网络整理
导读:我正在尝试使用返回元组的函数更新字典,其中第一个元素是字符串. def t():... return 'ABC',123 然而, dict.update 功能并不十分喜欢它. d = {} d.update(t())Traceback (most recent call last): File "stdin",line 1,in moduleValueError: dictionary upda
我正在尝试使用返回元组的函数更新字典,其中第一个元素是字符串.

>>> 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>",in <module>
  File "<stdin>",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'}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读