We can remove the last key-value pair from a dictionary using the in-built function popitem()
.
Key takeaways
In Python, dictionaries store data as key-value pairs, each key identifying a unique value.
Removing key-value pairs is important for handling data and keeping dictionaries up-to-date.
There are several methods for removing keys from dictionaries:
The
del
keyword: Directly removes a key-value pair by referencing the keyThe
popitem()
method: Removes the last inserted key-value pairThe
pop(key[, default])
method: Removes a specific key-value pair and optionally provides a default value if the key doesn’t exist
A dictionary contains a collection of indexes and values (indexes are also called keys). Each key is associated with a single value which helps in efficient retrieval. The association of a key and a value is called a key-value pair or an item.
new_dict = {'Color': 'Yellow', 'Type': 'Sun flower', 'Quantity': 50}
Here, 'Color'
, 'Type'
, and 'Quantity'
are keys, and 'Yellow'
, Sun flower
, and 50
are their corresponding values.
Dictionaries are used in various scenarios as listed below:
Many NoSQL databases, like Redis and MongoDB, store data as key-value pairs.
Web APIs commonly use key-value pairs to send data between servers and clients.
key-value pairs are used in configuration files to set parameters and options for applications.
Python provides support for the dictionary data structure. Understanding how to remove key-value pairs from a Python dictionary is necessary for removing obsolete or incorrect key-value pairs. There are several ways to remove a key-value pair from a dictionary as listed below:
Using the del
keyword
Using the pop()
method
There are also ways to remove multiple or all keys from a dictionary:
We can remove multiple keys from a dictionary using the pop()
method.
We can delete all Keys from a Dictionary using the del
keyword.
del
keywordThe del
keyword deletes a key-value pair from a dictionary.
We simply access the value that needs to be deleted and use the following syntax:
del dict[key]
If the key-value pair does not exist, a KeyError
exception is thrown.
# declare a dictionarydict1 = {1: "one", 2: "two", 3: "three", 4: "four"}print("Original Dictionary: ", dict1)# using del and giving the key as indexdel dict1[1]print("Dictionary after del: ", dict1)# using del and giving the key as indexdel dict1[3]print("Dictionary after del: ", dict1)
popitem()
methodThe built-in popitem()
method deletes the last key-value pair in a dictionary. We cannot specify the element that needs to be deleted. The function takes no arguments.
dict.popitem()
A KeyError
exception is thrown if the dictionary is empty. Otherwise, the key-value pair is returned as a tuple.
# declare a dictionarydict1 = {1: "one", 2: "two", 3: "three", 4: "four"}print("Original Dictionary: ", dict1)# using popitem()valDel = dict1.popitem()print("Dictionary after using popitem(): ", dict1)print("The key:value pair that was removed is: ", valDel)# using popitem()valDel = dict1.popitem()print("Dictionary after using popitem(): ", dict1)print("The key:value pair that was removed is: ", valDel)
pop()
methodThe built-in pop()
method deletes a specific key-value pair from a dictionary.
dict.pop(key[, default])
The function takes two arguments:
key
: The key of the value that needs to be deleted
default
: An optional argument (the default
value is returned if the key does not exist in the dictionary)
If the key does not exist and the default
argument is not given, a KeyError
exception is returned. This can be avoided using the second argument.
Otherwise, if the key exists, the value of the element removed is returned.
# declare a dictionarydict1 = {1: "one", 2: "two", 3: "three", 4: "four"}print("Original Dictionary: ", dict1)# using pop()valDel = dict1.pop(1)print("Dictionary after using pop(): ", dict1)print("The value that was removed is: ", valDel)# using pop()valDel = dict1.pop(3)print("Dictionary after using pop(): ", dict1)print("The value that was removed is: ", valDel)# using pop()valDel = dict1.pop(3, "No Key Found")print("Dictionary after using pop(): ", dict1)print("The value that was removed is: ", valDel)# using pop()# if default value not given, error will be raisedprint("Error raised: ")valDel = dict1.pop(3)
pop()
methodWe can delete multiple key-value pairs from the dictionary using the pop()
method in a for
loop. First, we declare an array of keys that need to be removed from the dictionary, then use a loop to iterate, and lastly remove them from the dictionary using the pop()
method one by one.
# declare a dictionarydict1 = {1: "one", 2: "two", 3: "three", 4: "four"}removeKeys = [2,3]for key in removeKeys:dict1.pop(key)print(dict1)
del
keywordWe can delete all the key-value pairs from a dictionary using the del
keyword as demonstrated in the code below:
# declare a dictionarydict1 = {1: "one", 2: "two", 3: "three", 4: "four"}print("Original Dictionary: ", dict1)del dict1try:print(test_dict)except:print('All elements are deleted!')
Quiz!
Which statement is correct for removing all the key-value pairs using the del
keyword?
delete dict_name
del dict_name[key]
del dict_name
del dict_name.delete()
In conclusion, knowing how to delete key-value pairs is an essential skill for managing data structures. Effective use of keywords/methods like del
, pop()
and popitem()
will help in data manipulation in our projects.
Haven’t found what you were looking for? Contact Us