我试图使用列表值作为(key , value)
对来更新字典。但是它不会更新并抛出一个TypeError:
user_dict = {"bob" : 30, "john": 40}
user_dict.update(["phill", 50])
print(user_dict)
ValueError:字典更新序列元素#0的长度为5;2是必需的
发布于 2020-12-12 11:01:13
您需要将每个键值对表示为可迭代的(例如。(一个元组(key1, value1)
),然后您需要将它包装成另一个可迭代的,然后就是您传入的那个。下面是dict.update
函数的文档:
更新(其他)
用其他键/值对更新字典,覆盖现有键。返回None
。
update()
接受另一个字典对象或可迭代的键/值对(作为元组或其他长度为2的可迭代性)。如果指定了关键字参数,则字典将使用以下键/值对:d.update(red=1, blue=2)
更新。
键值对可以是元组,然后可以传递它的列表:
In [4]: user_dict = {"bob" : 30, "john": 40}
In [5]: user_dict.update([ ('phill',50) ])
In [6]: user_dict
Out[6]: {'bob': 30, 'john': 40, 'phill': 50}
键值对也可以是一个列表,然后可以传递它的列表:
In [12]: user_dict = {"bob" : 30, "john": 40}
In [13]: user_dict.update([ ['phill',50] ])
In [14]: user_dict
Out[14]: {'bob': 30, 'john': 40, 'phill': 50}
键值也可以是元组,然后可以传递其中的一个元组(请注意,您需要添加,
的尾随以生成1的元组):
In [18]: user_dict = {"bob" : 30, "john": 40}
In [19]: user_dict.update(( ('phill',50), ))
In [20]: user_dict
Out[20]: {'bob': 30, 'john': 40, 'phill': 50}
为了使你的生活更简单,你可以通过一个映射(前)。(另一项决议):
In [1]: user_dict = {"bob" : 30, "john": 40}
In [2]: user_dict.update( {"phill": 50} )
In [3]: user_dict
Out[3]: {'bob': 30, 'john': 40, 'phill': 50}
https://stackoverflow.com/questions/65264096
复制相似问题