Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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!?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading