1. You can update many keys on the same statement.
my_dict.update(other_dict)
In this case you don't have to know how many keys are in the other_dict. You'll just be sure that all of them will be updated on my_dict.
2. You can use any iterable of key/value pairs with dict.update
As per the documentation you can use another dictionary, kwargs, list of tuples, or even generators that yield tuples of len 2.
3. You can use the update method as an argument for functions that expect a function argument.
Example:
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
Answer from Jundiaius on Stack Overflow1. You can update many keys on the same statement.
my_dict.update(other_dict)
In this case you don't have to know how many keys are in the other_dict. You'll just be sure that all of them will be updated on my_dict.
2. You can use any iterable of key/value pairs with dict.update
As per the documentation you can use another dictionary, kwargs, list of tuples, or even generators that yield tuples of len 2.
3. You can use the update method as an argument for functions that expect a function argument.
Example:
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
d.update(n) is basically an efficient implementation of the loop
for key, value in n.items():
d[key] = value
But syntactically, it also lets you specify explicit key-value pairs without building a dict, either using keyword argumetns
d.update(a=1, b=2)
or an iterable of pairs:
d.update([('a', 1), ('b', 2)])
defaultdict vs update
Looping through multiple nested dictionaries and updating a key:value pair if condition is met
Videos
Python has this feature built-in:
>>> d = {'b': 4}
>>> d.update({'a': 2})
>>> d
{'a': 2, 'b': 4}
Or given you're not allowed to use dict.update:
>>> d = dict(d.items() + {'a': 2}.items()) # doesn't work in python 3
With python 3.9 you can use an |= update operator:
>>> d = {'b': 4}
>>> d |= {'a': 2}
>>> d
{'a': 2, 'b': 4}