A dictionary in Python is a collection that is ordered, changeable, and does not allow duplicate keys. It is used to store data values in key-value pairs. Dictionaries are written with curly brackets. An example is given below:
sample_dict = {"type": "Writing","language": "English","year": 2021}
Python allows a dictionary object to be mutable, meaning update or add operations are permissible. A new item can be pushed or an existing item can be modified with the aid of an assignment operator.
If an element is added to a key that already exists, its value will be changed to the newly added value. Upon adding a fresh key-value pair, a new item will be added to the existing dictionary.
The different methods to update a dictionary are:
The example below demonstrates both the addition and update operations on the existing dictionary object.
my_dict = {'Name': 'Henry', 'Age': 16, 'Subject': 'English'}print("The student who left is", my_dict.get('Name'))my_dict['Name'] = 'Perry'print("The student who replaced him is", my_dict.get('Name'))my_dict['Name'] = 'Smith'print("The student who joined is", my_dict.get('Name'))
sample_dict = {"java" : 1, "python" : 2, "nodejs" : 3}sample_dict.update( nodejs = 2 )print(sample_dict)sample_dict.update( python = 3 )print(sample_dict)
Several methods are provided by Python to remove items/elements from a dictionary. They include:
pop()
method:pop()
takes a key as an input and deletes the corresponding item/element from the Python dictionary. It returns the value associated with the input key.popitem()
method:clear()
method:clear()
is referred to as the flush
method because it flushes everything from the dictionary.del
method:del
keyword. del
deletes individual elements and eventually the entire dictionary object.food_items = {1:"rice", 2:"beans", 3:"yam", 4:"plantain", 5:"potatoes", 6:"wheat"}# Delete a specific elementprint(food_items.pop(6))print(food_items)# Delete a random elementprint(food_items.popitem())print(food_items)# Remove a specific elementdel food_items[4]print(food_items)# Delete all elements from the dictionaryfood_items.clear()print(food_items)# Eliminates the whole dictionary objectdel food_items
The
clear()
method above removes all the elements from the Python dictionary, leaving it empty. Hence, the subsequent call for thedel
method on the dictionary object removes it altogether. So, addingprint(food_items)
afterdel food_items
fails and returns aNameError
.