A dictionary contains the pair of the keys & values (represents key : value), a dictionary is created by providing the elements within the curly braces ({}), separated by the commas.
Here, we are going to learn the different ways to change the dictionary items,
- Direct (simple) way to change the dictionary items
- Using the update() method to change the dictionary items
1) Direct (simple) way to change the dictionary items
The simple way is to change the dictionary items – assign the new value by referring to the key of the dictionary.
Syntax:
Program:
Output:
Dictionary 'dict_a' is... {'name': 'Amit', 'id': 101, 'age': 21} Updated Dictionary 'dict_a' is... {'name': 'Shivang Yadav', 'id': 101, 'age': 23}2) Using the update() method to change the dictionary items
The update() method can also be used to change the dictionary items. The update method accepts the key: value pair.
Syntax:
dictionary_name.update({key:value})Program:
Output:
Dictionary 'dict_a' is... {'id': 101, 'name': 'Amit', 'age': 21} Updated Dictionary 'dict_a' is... {'id': 101, 'name': 'Shivang Yadav', 'age': 23}need an explanation for this answer? contact us directly to get an explanation for this answer