How to Remove a Key from Python Dictionary

We can remove the key from the Python dictionary using the del keyword. Using this keyword we can delete objects like a list, slice a list, and delete dictionaries. We know that in Python everything is an object so we can remove key-value pairs objects from a dictionary.

Using the del keyword we can remove specified key-value pair/whole dictionary. In this article, I will explain the del keyword and using this how we can remove the specified key/whole keys of the dictionary.

1. Quick Examples of Remove a Key from Dictionary

Following are quick examples of removing a key from the Dictionary.


# Below are the quick examples

# Example 1: Remove key using del keyword
del my_dict['fee']

# Example 2: Emove the key using pop()
print("Before removing the key in a Dictionary:\n", my_dict)
my_dict.pop('duration')

# Example 3: Using dictionary comprehension and items() 
# Remove the key from dictionary
print("Before removing the key in a Dictionary:\n", my_dict)
new_dict = {key: val for key,
			val in my_dict.items() if key != 'course'}
print("After removing the key in a Dictionary:\n ", new_dict) 

# Example 4: Remove key using dictionary comprehension
new_dict = {key: my_dict[key] for key in my_dict if key != 'course'}
print("After removing the key in a Dictionary:\n ", new_dict) 

# Example 5: Remove all keys using del 
my_dict = {'course':'python','fee':4000,'duration':'60days'}
# empty the dictionary 
del my_dict

# Example 6: Remove all keys using clear()
my_dict = {'course':'python','fee':4000,'duration':'60days'}
# empty the dictionary 
my_dict.clear()

2. What is Python Dictionary

A Python dictionary is a collection that is unordered, mutable and does not allow duplicates. Each element in the dictionary is in the form of key:value pairs. Dictionary elements should be enclosed with {} and key: value pair separated by commas. The dictionaries are indexed by keys.

Moreover, dictionaries are mutable data types, which means that you can be added, deleted, and updated their key:value pairs. keys are an immutable type such as string, numbers(int, float), and tuple. In case, you add duplicates, it will update the existing key with the new value.


# Create dictionary
my_dict = {'course':'python','fee':4000,'duration':'60days'}
print(my_dict)

Yields below output.

Python dictionary remove keys
Python Dictionary

3. Python Remove Key from Dictionary using del Keyword

We can use a del keyword to remove the specified key from the dictionary in Python. Use the del keyword along with the key of the dictionary to remove the specified key-value pair from the dictionary. After removing the key-value pair let’s print the given dictionary with the remaining key-value pairs. For example,


# Remove key using del keyword
del my_dict['fee']
print(my_dict)

Yields below output. Note that removing a key actually removes the key and the value associated with it.

Python dictionary remove key
Python Dictionary

4. Remove Key from Dictionary using pop()

The Python dictionary pop() function is another method that can be used to remove the element from the dictionary by dict key and return the value related to the removed key. If a key does not exist in the dictionary and the default value is specified, then returns the default value; else throws a KeyError.

Let’s pop the specified key from the Python dictionary using the pop() function.


# Remove the key using pop()
print("Before removing the key:\n", my_dict)
value = my_dict.pop('duration')
print("Popped Value: ", value)
print("After removing the key:\n", my_dict)

Yields below output.

python remove key from dictionary

5. Using items() & Dictionary Comprehension to Remove Key

Alternatively, use dictionary comprehension along with the items() function in Python to remove the desired key from the dictionary. In order to create a new dictionary after removing the specified key-value pair from the original dictionary use the items() function and dictionary comprehension is used to create dictionaries using iterables.


# Using dictionary comprehension and items() 
# Remove the key from dictionary
print("Before removing the key:\n", my_dict)
new_dict = {key: val for key,val
     in my_dict.items() if key != 'course'}
print("After removing the key:\n ", new_dict) 

Yields below output.


# Output:
Before removing the key:
 {'course': 'python', 'fee': 4000, 'duration': '60days'}
After removing the key:
  {'fee': 4000, 'duration': '60day

 6. Use Dictionary Comprehension to Remove a Key

In the above example, we use the dict.items with for loop to get each item from the dictionary. Here, Let’s use dictionary comprehension to iterate the given dictionary then remove the key-value pair of specified and returns the new dictionary with the remaining key-value pairs of an original dictionary.


# Remove key using dictionary comprehension
new_dict = {key: my_dict[key] for key in my_dict if key != 'course'}
print("After removing the key in a Dictionary:\n ", new_dict) 

# Output: 
# After removing the key in a Dictionary:
# {'fee': 4000, 'duration': '60days'}

7. Using For Loop to Remove the Key

We can also use a for loop to remove a key from a dictionary. For example,


# Remove key using for loop
new_dict = {}
for key, value in my_dict.items():
	if key != 'fee':
		new_dict[key] = value
print(new_dict)

# Output:
# {'course': 'python', 'duration': '60days'}

8. Remove Multiple Keys from the Dictionary

All the above examples are converted by removing a single key from the dic, let’s also see an example of how to remove multiple keys from the dictionary.


# Remove multiple keys
print("Before removing the key:\n", my_dict)
keys_list = ["course","duration"]
for key in keys_list:
    del my_dict[key]
    
print("After removing the keys:\n", my_dict)

# Output:
# Before removing the key:
#  {'course': 'python', 'fee': 4000, 'duration': '60days'}
# After removing the keys:
#  {'fee': 4000}

9. Remove All Keys from Dictionary using del

Using the del keyword we can remove all key-value pairs from a dictionary.


# Remove all keys using del 
my_dict = {'course':'python','fee':4000,'duration':'60days'}

# Empty the dictionary 
del my_dict

10. Delete all Keys from Dictionary using clear()

The Python dictionary clear() function is used to remove all key-value pairs from the dictionary. The clear() function doesn’t return any value.


# Remove all keys using clear()
my_dict = {'course':'python','fee':4000,'duration':'60days'}

# Empty the dictionary 
my_dict.clear()
print("Length", len(my_dict))
print(my_dict)

# Output:
# Length 0
# {}

11. Conclusion

In this article, I have explained the Python del keyword and using this how we can remove the specified key from the dictionary. And also explained how to remove the keys from the dictionary using the pop() function, dictionary comprehension, clear(), and items() functions with examples.

Happy learning !!

Related Articles

References

Vijetha

With 5 of experience in technical writing, I have had the privilege to work with a diverse range of technologies like Python, Pandas, NumPy and R. During this time, I have consistently demonstrated my ability to grasp intricate technical details and transform them into comprehensible materials.

Leave a Reply

You are currently viewing How to Remove a Key from Python Dictionary