In Python programming, dictionaries are a useful data structure for storing key-value pairs. Once we have created a dictionary and added elements to it, we may need to retrieve specific values or remove items one by one or altogether from the dictionary. This topic will explore various methods that can help us accomplish these tasks efficiently.
Getting and removing items
We know how to create a dictionary and add elements to it. But what if we need to get some value from the dictionary or also remove an item? The following methods will help you deal with different tasks depending on your needs.
1. Get a value from the dictionary by a key.
As you remember, we can access the value in a dictionary by a key:
testable = {}
testable['September'] = '16°C'
print(testable['September']) # 16°C
However, if you try to access a non-existent key, you will get a KeyError:
print(testable['June']) # throws a KeyError
To avoid the KeyError, we can use the get method that returns None if the specified key is not in the dictionary:
# 'get' method does not throw an error
print(testable.get('September')) # 16°C
print(testable.get('June')) # None
With the get method, we can also define the default value that will be returned in such a case:
print(testable.get('June', 'no temperature')) # no temperature
2. Remove the key from the dictionary and return the value using the pop method.
If the specified key was found in the dictionary, then the method will remove it and return the value:
testable = {'September': '16°C', 'December': '-10°C'}
return_value = testable.pop('December')
print(return_value) # -10°C
print(testable) # {'September': '16°C'}
If the key was not found, a KeyError will appear:
testable.pop('July') # throws a KeyError
To get rid of it, we can provide a default argument, and it will return this default value:
return_value = testable.pop('July', 'no temperature')
print(return_value) # no temperature
3. Remove and return the last item (key, value) added to the dictionary using the popitem method:
testable = {'September': '16°C', 'December': '-10°C'}
return_value = testable.popitem()
print(return_value) # ('December', '-10°C')
print(testable) # {'September': '16°C'}
Pay attention, if the dictionary is empty, a KeyError will appear:
testable = {}
return_value = testable.popitem()
# KeyError: 'popitem(): dictionary is empty'
Before Python 3.7, the popitem method removes and returns a random item from the dictionary, not the last one added.
Cleaning the dictionary
All the methods described above return a value or an item (key, value) upon removing, but sometimes this is not what we want. There are two ways that remove an item from the dictionary (they do not return anything) or the entire dictionary content at once.
1. Delete (remove from a dictionary) a value by its key with the del keyword:
testable = {'September': '16°C', 'December': '-10°C', 'July': '23°C'}
# this will remove both the key and the value from dictionary object
del testable['September']
print(testable) # {'December': '-10°C', 'July': '23°C'}
# throws a KeyError because there's no such key in the dictionary
del testable['May']
# throws a KeyError, as we've already deleted the object by the key
del testable['September']
# deletes the whole dictionary
del testable
2. Remove all the items and return an empty dictionary using the clear method:
testable = {'September': '16°C', 'December': '-10°C', 'July': '23°C'}
testable.clear() # remove all elements
print(testable) # {}Differences in removal methods
You may wonder, is there any difference between dict = {} and dict.clear() ? Let's say we have another variable that refers to the same dictionary:
testable = {'December': '-10°C', 'July': '23°C'}
another_testable = testable
Then, the dict = {} just creates a new empty dictionary and assigns it to our variable. Let's go back to the example above and assign an empty dictionary to testable:
testable = {}
print(testable) # {}
print(another_testable) # {'December': '-10°C', 'July': '23°C'}
another_testable still points to the original dictionary with the same elements, so it doesn't change.
In contrast, the clear method will clear the dictionary as well as all the objects referring to it:
testable = {'December': '-10°C', 'July': '23°C'}
another_testable = testable
testable.clear()
print(testable) # {}
print(another_testable) # {}Summary
In this topic, we discussed methods for getting values from a dictionary and removing items from it. We learned about the get method, which allows us to retrieve values from a dictionary by a key while avoiding KeyError exceptions. The pop method enables us to remove a key-value pair from the dictionary and retrieve the associated value. Additionally, the popitem method removes and returns the last item added to the dictionary.
We also explored two ways to clean a dictionary: using the del keyword to remove a specific item by its key and the clear method to remove all items from the dictionary. We also highlighted the difference between assigning an empty dictionary to a variable and using the clear method, emphasizing that the latter clears the dictionary and all objects referring to it.
By understanding these methods, developers can effectively manipulate dictionaries, retrieve values, and remove items as needed, enhancing their ability to work with this data structure in Python.