为什么我们需要 python 中的 dict.update() 方法而不是仅仅将值分配给相应的键?

Den*_*rım 12 python dictionary

我一直在使用字典,我必须在代码的不同部分中修改它们。我试图确保我是否没有错过任何有关在任何情况下都不需要 dict_update() 的内容。

因此,使用 update() 方法的原因是向当前字典添加新的键值对,或者更新现有键值对的值。

可是等等!?

难道他们不已经可以通过这样做:

>>>test_dict = {'1':11,'2':1445}
>>>test_dict['1'] = 645
>>>test_dict
{'1': 645, '2': 1445}
>>>test_dict[5]=123
>>>test_dict
{'1': 645, '2': 1445, 5: 123}
Run Code Online (Sandbox Code Playgroud)

在什么情况下使用它至关重要?我好奇。

非常感谢

Jun*_*ius 20

1. 您可以在同一条语句上更新多个键。

my_dict.update(other_dict)
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您不必知道other_dict. 您只需确保所有这些都将在 上更新my_dict

2.您可以将任何可迭代的键/值对与 dict.update 一起使用

根据文档,您可以使用另一个字典、kwargs、元组列表,甚至生成 len 2 元组的生成器。

3. 您可以将该update方法用作需要函数参数的函数的参数。

例子:

def update_value(key, value, update_function):
    update_function([(key, value)])

update_value("k", 3, update_on_the_db)  # suppose you have a update_on_the_db function
update_value("k", 3, my_dict.update)  # this will update on the dict
Run Code Online (Sandbox Code Playgroud)


che*_*ner 12

d.update(n)基本上是循环的有效实现

for key, value in n.items():
    d[key] = value
Run Code Online (Sandbox Code Playgroud)

但从语法上讲,它还允许您指定显式键值对,而无需构建dict,或者使用关键字参数

d.update(a=1, b=2)
Run Code Online (Sandbox Code Playgroud)

或可迭代的对:

d.update([('a', 1), ('b', 2)])
Run Code Online (Sandbox Code Playgroud)