How to remove a key value pair from a dictionary in Python

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 key

    • The popitem() method: Removes the last inserted key-value pair

    • The 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.

Where are dictionaries used?

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:

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.

Method 1: Remove a key-value pair from a dictionary using the del keyword

The 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 dictionary
dict1 = {1: "one", 2: "two", 3: "three", 4: "four"}
print("Original Dictionary: ", dict1)
# using del and giving the key as index
del dict1[1]
print("Dictionary after del: ", dict1)
# using del and giving the key as index
del dict1[3]
print("Dictionary after del: ", dict1)

Method 2: Remove a key-value pair from a dictionary using the popitem() method

The 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 dictionary
dict1 = {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)

Method 3: Remove a key-value pair from a dictionary using the pop() method

The built-in pop() method deletes a specific key-value pair from a dictionary.


dict.pop(key[, default])

The function takes two arguments:

  1. key: The key of the value that needs to be deleted

  2. 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 dictionary
dict1 = {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 raised
print("Error raised: ")
valDel = dict1.pop(3)

Method 4: Remove multiple keys from a dictionary using the pop() method

We 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 dictionary
dict1 = {1: "one", 2: "two", 3: "three", 4: "four"}
removeKeys = [2,3]
for key in removeKeys:
dict1.pop(key)
print(dict1)

Method 5: Delete all key-value pairs from a dictionary using the del keyword

We can delete all the key-value pairs from a dictionary using the del keyword as demonstrated in the code below:

# declare a dictionary
dict1 = {1: "one", 2: "two", 3: "three", 4: "four"}
print("Original Dictionary: ", dict1)
del dict1
try:
print(test_dict)
except:
print('All elements are deleted!')

Quiz!

1

Which statement is correct for removing all the key-value pairs using the del keyword?

A)

delete dict_name

B)

del dict_name[key]

C)

del dict_name

D)

del dict_name.delete()

Question 1 of 30 attempted

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.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How do we remove the last key-value pair from a dictionary in Python?

We can remove the last key-value pair from a dictionary using the in-built function popitem().


How do we remove elements from a set in Python?

We can remove elements from a set using the Python remove() method.

colors = {"yellow", "green", "red"}
colors.remove("green")
print(colors)

What happens if we try to remove a key that does not exist in the dictionary?

If we try to remove a key that does not exist, a KeyError exception is raised.


How do we sort a dictionary by value in Python?

We can sort a dictionary by value in Python using the sorted() method:

dict1 = {1: "one", 2: "two", 3: "three", 4: "four"}

lst = dict1.values()

#Sorted by value
print("Sorted by value: ", sorted(lst))

How do we check if a dictionary is empty in Python?

We can check if a dictionary is empty using a simple if not statement or the len() function.

if not newDict:
    print("Dictionary is empty")
//or
if len(newDict) == 0:
    print("Dictionary is empty")

What is a Python hash table?

A Python hash table contains key-value pairs, but the key is created using a hashing function. As a result, a data element’s search and insertion functions become considerably faster, since the key values themselves become the index of the array that holds the data.


Free Resources