Home > OS >  Why do we need a dict.update() method in python instead of just assigning the values to the correspo
Why do we need a dict.update() method in python instead of just assigning the values to the correspo

Time:01-20

I have been working with dictionaries that I have to modify within different parts of my code. I am trying to make sure if I do not miss anything about there is no need for dict_update() in any scenario.

So the reasons to use update() method is either to add a new key-value pair to current dictionary, or update the value of your existing ones.

But wait!?

Aren't they already possible by just doing:

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

In what case it would be crucial to use it ? I am curious.

Many thanks

CodePudding user response:

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)])

CodePudding user response:

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
  •  Tags:  
  • Related