The Wayback Machine - https://web.archive.org/web/20240713143053/https://www.geeksforgeeks.org/python-ways-to-remove-a-key-from-dictionary/
Open In App

Python | Ways to remove a key from dictionary

Last Updated : 20 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Dictionary is used in manifold practical applications such as day-day programming, web development, and AI/ML programming as well, making it a useful container overall. Hence, knowing shorthands for achieving different tasks related to dictionary usage always is a plus. This article deals with one such task of deleting/removing a dictionary key-value pair from a dictionary, we will discuss different methods to deal given task, and in Last we will see how can we delete all keys from Dictionary.

Example:

Before remove key:   {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22, 'Mani': 21}

Operation Perform:   del test_dict['Mani']

After removing key:  {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22}

Method 1: Remove a Key from a Dictionary using the del

The del keyword can be used to in-place delete the key that is present in the dictionary in Python. One drawback that can be thought of using this is that it raises an exception if the key is not found and hence non-existence of the key has to be handled. Demonstrating key-value pair deletion using del.

Python
# Initializing dictionary
test_dict = {"Arushi": 22, "Mani": 21, "Haritha": 21}

# Printing dictionary before removal
print("The dictionary before performing remove is : ", test_dict)

# Using del to remove a dict
# removes Mani
del test_dict['Mani']

# Printing dictionary after removal
print("The dictionary after remove is : ", test_dict)

# Using del to remove a dict
# raises exception
del test_dict['Mani']

Output :

The dictionary before performing remove is :  {'Arushi': 22, 'Mani': 21, 'Haritha': 21}
The dictionary after remove is :  {'Arushi': 22, 'Haritha': 21}

Exception : 

Traceback (most recent call last):
  File "/home/44db951e7011423359af4861d475458a.py", line 20, in 
    del test_dict['Mani']
KeyError: 'Mani'

The time complexity of initializing the dictionary and removing an item from the dictionary using the “del” statement is O(1). 

The auxiliary space required for this code is O(1), as we are only modifying the existing dictionary and not creating any new data structures.

Method 2: Remove a Key from a Dictionary using pop() 

The pop() can be used to delete a key and its value inplace. The advantage over using del is that it provides the mechanism to print desired value if tried to remove a non-existing dict. pair. Second, it also returns the value of the key that is being removed in addition to performing a simple delete operation. Demonstrating key-value pair deletion using pop() 

Python
# Initializing dictionary
test_dict = {"Arushi": 22, "Anuradha": 21, "Mani": 21, "Haritha": 21}

# Printing dictionary before removal
print("The dictionary before performing remove is : " + str(test_dict))

# Using pop() to remove a dict. pair
# removes Mani
removed_value = test_dict.pop('Mani')

# Printing dictionary after removal
print("The dictionary after remove is : " + str(test_dict))
print("The removed key's value is : " + str(removed_value))

print('\r')

# Using pop() to remove a dict. pair
# doesn't raise exception
# assigns 'No Key found' to removed_value
removed_value = test_dict.pop('Manjeet', 'No Key found')

# Printing dictionary after removal
print("The dictionary after remove is : " + str(test_dict))
print("The removed key's value is : " + str(removed_value))

Output:

The dictionary before performing remove is : {'Arushi': 22, 'Anuradha': 21,
 'Mani': 21, 'Haritha': 21}
The dictionary after remove is : {'Arushi': 22, 'Anuradha': 21, 'Haritha': 21}
The removed key's value is : 21

The dictionary after remove is : {'Arushi': 22, 'Anuradha': 21, 'Haritha': 21}
The removed key's value is : No Key found

Time Complexity: O(1)
Auxiliary Space: O(1)

Method 3: Using items() + dict comprehension to Remove a Key from a Dictionary

items() coupled with dict comprehension can also help us achieve the task of key-value pair deletion but, it has the drawback of not being an in-place dict. technique. Actually, a new dict is created except for the key we don’t wish to include. Demonstrating key-value pair deletion using items() + dict comprehension.

Python
# Initializing dictionary
test_dict = {"Arushi": 22, "Anuradha": 21, 
             "Mani": 21, "Haritha": 21}

# Printing dictionary before removal
print("The dictionary before performing\
remove is : " + str(test_dict))

# Using items() + dict comprehension to remove a dict. pair
# removes Mani
new_dict = {key: val for key, 
            val in test_dict.items() if key != 'Mani'}

# Printing dictionary after removal
print("The dictionary after remove is : " + str(new_dict))

Output:

The dictionary before performing remove is : {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22, 'Mani': 21}
The dictionary after remove is : {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22}

Time Complexity: O(n), where n is the length of the list test_dict
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list

Method 4: Use a Python Dictionary Comprehension to Remove a Key from a Dictionary

In this example, we will use Dictionary Comprehension to remove a key from a dictionary.

Python
# Initializing dictionary
test_dict = {"Arushi": 22, "Anuradha": 21, "Mani": 21, "Haritha": 21}

# Printing dictionary before removal
print("The dictionary before performing remove is : \n" + str(test_dict))

a_dict = {key: test_dict[key] for key in test_dict if key != 'Mani'}

print("The dictionary after performing remove is : \n", a_dict)

Output:

The dictionary before performing remove is : 
{'Arushi': 22, 'Anuradha': 21, 'Mani': 21, 'Haritha': 21}
The dictionary after performing remove is : 
 {'Arushi': 22, 'Anuradha': 21, 'Haritha': 21}

Method 5: Iterating and Eliminating

In this example, we will use a loop to remove a key from a dictionary.

Python
# Initializing dictionary
test_dict = {"Arushi": 22, "Anuradha": 21, "Mani": 21, "Haritha": 21}
print(test_dict)

# empty the dictionary d
y = {}
# eliminate the unrequired element
for key, value in test_dict.items():
    if key != 'Arushi':
        y[key] = value
print(y)

Output:

{'Arushi': 22, 'Anuradha': 21, 'Mani': 21, 'Haritha': 21}
{'Anuradha': 21, 'Mani': 21, 'Haritha': 21}

How to Delete all Keys from a Dictionary?

Method 1: Delete all Keys from a Dictionary using the del

The del keyword can also be used to delete a list, slice a list, delete dictionaries, remove key-value pairs from a dictionary, delete variables, etc.

Python
# Initializing dictionary
test_dict = {"Arushi": 22, "Anuradha": 21, "Mani": 21, "Haritha": 21}
print(test_dict)

# empty the dictionary d
del test_dict
try:
    print(test_dict)
except:
    print('Deleted!')

Output:

{'Arushi': 22, 'Anuradha': 21, 'Mani': 21, 'Haritha': 21}
Deleted!

Method 2: Delete all Keys from a Dictionary using dict.clear()

The clear() method removes all items from the dictionary. The clear() method doesn’t return any value.

Python
# Initializing dictionary
test_dict = {"Arushi": 22, "Anuradha": 21, "Mani": 21, "Haritha": 21}
print(test_dict)

# empty the dictionary d
test_dict.clear()
print("Length", len(test_dict))
print(test_dict)

Output:

{'Arushi': 22, 'Anuradha': 21, 'Mani': 21, 'Haritha': 21}
Length 0
{}

Time complexity: O(1)

Auxiliary Space: O(1)

Python | Ways to remove a key from dictionary- FAQs

How to get rid of dict_keys in Python?

In Python, dict_keys is a view object that provides a dynamic view of the keys in a dictionary. To convert it into a list of keys or directly iterate over keys, you can use the list() constructor or iterate over the dictionary itself:

  • Convert dict_keys to a list of keys:
my_dict = {'a': 1, 'b': 2, 'c': 3}
keys_list = list(my_dict.keys())
print(keys_list)  # Output: ['a', 'b', 'c']
  • Iterate over keys without converting to a list:
for key in my_dict:
    print(key)

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

If you try to remove a key that does not exist in a dictionary using the del statement or the pop() method, Python will raise a KeyError:

  • Using del statement:
my_dict = {'a': 1, 'b': 2}
del my_dict['c']  # KeyError: 'c'
  • Using pop() method:
my_dict = {'a': 1, 'b': 2}
value = my_dict.pop('c')  # KeyError: 'c'

To safely remove a key if it exists, you can use dict.get() method with a default value or check for the key’s existence before attempting to remove it.

Can I remove a key from a dictionary while iterating over it?

Yes, you can remove a key from a dictionary while iterating over it, but you need to be cautious. Modifying a dictionary size during iteration can lead to unexpected results or errors. To safely remove keys, iterate over a copy of the keys or use a list comprehension:

  • Iterate over a copy of keys:
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key in list(my_dict.keys()):  # Create a copy of keys
    if key == 'b':
        del my_dict[key]
print(my_dict)  # Output: {'a': 1, 'c': 3}
  • Using list comprehension:
my_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict = {key: value for key, value in my_dict.items() if key != 'b'}
print(my_dict)  # Output: {'a': 1, 'c': 3}

How to remove a key in JSON Python?

JSON (JavaScript Object Notation) is primarily a data format for serialization. In Python, after parsing JSON data into a dictionary using json.loads(), you can remove a key using standard dictionary methods like del or pop():

  • Using del statement:
import json
json_data = '{"name": "John", "age": 30}'
my_dict = json.loads(json_data)
del my_dict['age']
print(my_dict)  # Output: {'name': 'John'}
  • Using pop() method:
import json

json_data = '{"name": "John", "age": 30}'
my_dict = json.loads(json_data)
value = my_dict.pop('age')
print(my_dict)  # Output: {'name': 'John'}

How do you remove keys from a set in Python?

In Python, sets are unordered collections of unique elements. To remove an element (key) from a set, use the remove() method. If the element does not exist, it raises a KeyError. Alternatively, use discard() to safely remove an element without raising an error if it doesn’t exist:

  • Using remove() method:
my_set = {1, 2, 3, 4, 5}
my_set.remove(3)
print(my_set)  # Output: {1, 2, 4, 5}
  • Using discard() method:
my_set = {1, 2, 3, 4, 5}
my_set.discard(3)
print(my_set)  # Output: {1, 2, 4, 5}


    Previous Article
    Next Article

    Similar Reads

    Python | Remove item from dictionary when key is unknown
    Dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. It is widely used in day to day programming, web development, and machine learning. Let's discuss the various ways to remove items from the dictionary when key is unknown. Method #1 : Using n
    6 min read
    Python - Remove Key from Dictionary List
    Sometimes, while working with Python dictionaries, we can have a problem in which we need to remove a specific key from a dictionary list. This kind of problem is very common and has application in almost all domains including day-day programming and web development domain. Let's discuss certain ways in which this task can be performed. Method #1 :
    7 min read
    Python - Remove Dictionary Key Words
    Sometimes, while working with Python strings, we can have a problem in which we need to remove all the words from a string that is part of the key of the dictionary. This problem can have applications in domains such as web development and day-day programming. Let's discuss certain ways in which this task can be performed. Method #1: Using split()
    7 min read
    How to use a List as a key of a Dictionary in Python 3?
    In Python, we use dictionaries to check if an item is present or not . Dictionaries use key:value pair to search if a key is present or not and if the key is present what is its value . We can use integer, string, tuples as dictionary keys but cannot use list as a key of it . The reason is explained below . How does Python Dictionaries search their
    3 min read
    Python | Get key from value in Dictionary
    Let's see how to get the key by value in Python Dictionary. Example: One-Liner code C/C++ Code # creating a new dictionary my_dict ={"Java":100, "Python":112, "C":11} # one-liner print("One line Code Key value: ", list(my_dict.keys()) [list(my_dict.values()).index(100)]) Output: Java Extract Key from Python D
    6 min read
    Python - Dictionary Key's Product in list
    Many operations such as grouping and conversions are possible using Python dictionaries. But sometimes, we can also have a problem in which we need to perform the product of values of key in the dictionary list. This task is common in day-day programming. Let’s discuss certain ways in which this task can be performed. Method #1 : Using loop + list
    6 min read
    Group List of Dictionary Data by Particular Key in Python
    Group List of Dictionary Data by Particular Key in Python can be done using itertools.groupby() method. Itertools.groupby() This method calculates the keys for each element present in iterable. It returns key and iterable of grouped items. Syntax: itertools.groupby(iterable, key_func) Parameters: iterable: Iterable can be of any kind (list, tuple,
    3 min read
    Python Program to find XOR of all the key value pairs in a Dictionary
    Given a dictionary in python, write a program to find the XOR of all the key-value pairs in the dictionary and return in the form of an array. Note: All the keys and values in the dictionary are integers. Examples: Input : dic={1:3, 4:5, 6:7, 3 :8} Output : [2, 1, 1, 11] Explanation: XOR of all the key-value pairs in the dictionary are [1^3, 4^5, 6
    3 min read
    Dictionary with Tuple as Key in Python
    In Python, dictionaries are versatile data structures that allow you to store and retrieve data efficiently using key-value pairs. While it's common to use simple types like strings or integers as keys, you can also use more complex data structures, such as tuples. In this article, we'll explore five different methods to create and manipulate dicti
    2 min read
    Check if a Given Key Already Exists in a Python Dictionary
    Python dictionary can not contain duplicate keys so it is very crucial to check if a key is already present in the dictionary. If you accidentally assign a duplicate key value, the new value will overwrite the old one. So in a given dictionary, our task is to check if the given key already exists in a dictionary or not. If present, print "present"
    5 min read
    three90RightbarBannerImg