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:
dictionary_name[key] = new_value
Program:
# Python program to change the dictionary items
# creating the dictionary
dict_a = {'id' : 101, 'name' : 'Amit', 'age': 21}
# printing the dictionary
print("Dictionary \'dict_a\' is...")
print(dict_a)
# updating the values of name and age
dict_a['name'] = 'Shivang Yadav'
dict_a['age'] = 23
# printing the dictionary
# after changing the values
print("Updated Dictionary \'dict_a\' is...")
print(dict_a)
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:
# Python program to change the dictionary items
# using the update() method
# creating the dictionary
dict_a = {'id' : 101, 'name' : 'Amit', 'age': 21}
# printing the dictionary
print("Dictionary \'dict_a\' is...")
print(dict_a)
# updating the values of name and age
# using the update() method
dict_a.update({'name': 'Shivang Yadav'})
dict_a.update({'age': 23})
# printing the dictionary
# after changing the values
print("Updated Dictionary \'dict_a\' is...")
print(dict_a)
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:
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:
Program:
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer