update() method of dictionary

All dictionary methods

update(), takes one arguments , iterable object.

Returns : Nothing is returned .

The original dictionary is changed after this method.

Adding new key value pair

my_dict={'a':'One','b':'Two','c':'Three'}
my_dict2={'d':'Four'} # new key 
my_dict.update(my_dict2)
print(my_dict)
Output is here
{'a': 'One', 'b': 'Two', 'c': 'Three', 'd': 'Four'}

If input key available then value is updated.

my_dict={'a':'One','b':'Two','c':'Three'}
my_dict2={'b':'New value'} # existing key 
my_dict.update(my_dict2)
print(my_dict)
Output (key b with New value is updated )
{'a': 'One', 'b': 'New value', 'c': 'Three'}

Adding new keys with values

my_dict={'a':'One','b':'Two','c':'Three'}
my_dict.update(d='Four',e='Five')
print(my_dict)
Output
{'a': 'One', 'b': 'Two', 'c': 'Three', 'd': 'Four', 'e': 'Five'}

Adding and updating values

We can add new key with values and update existing values by using update()
my_dict={'a':'One','b':'Two','c':'Three'}
my_dict.update(b='New one',d='Four',e='Five')
print(my_dict)
Output ( value of key b is updated and new keys d and e added )
{'a': 'One', 'b': 'New one ', 'c': 'Three', 'd': 'Four', 'e': 'Five'}

All dictionary methods


plus2net.com



Post your comments , suggestion , error , requirements etc here





Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2021 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer