Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need a dict.update() method in python instead of just assigning the values to the corresponding keys?

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}

When would it be crucial to use it?

like image 344
Deniz yıldırım Avatar asked Sep 06 '25 00:09

Deniz yıldırım


1 Answers

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
like image 164
Jundiaius Avatar answered Sep 07 '25 15:09

Jundiaius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!