« 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
← Subscribe to our YouTube Channel here