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 - Extract Key's Value, if Key Present in List and Dictionary
    Given a list, dictionary, and a Key K, print the value of K from the dictionary if the key is present in both, the list and the dictionary. Input : test_list = ["Gfg", "is", "Good", "for", "Geeks"], test_dict = {"Gfg" : 5, "Best" : 6}, K = "Gfg" Output : 5 Explanation : "Gfg" is present in list and has value 5 in dictionary. Input : test_list = ["G
    11 min read
    Python - Combine two dictionaries having key of the first dictionary and value of the second dictionary
    Given two dictionaries. The task is to merge them in such a way that the resulting dictionary contains the key from the first dictionary and the value from the second dictionary. Examples: Input : test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}, test_dict2 = {"Gfg2" : 26, "is2" : 20, "best2" : 70} Output : {'Gfg': 26, 'is': 20, 'best': 70} Expla
    8 min read
    Python Program to Remove Nth element from Kth key's value from the dictionary
    Given a dictionary with value lists, our task is to write a Python program to remove N element from Kth key's values. Examples: Input : test_dict = {"gfg" : [9, 4, 5, 2, 3, 2], "is" : [1, 2, 3, 4, 3, 2], "best" : [2, 2, 2, 3, 4]}, K, N = "gfg", 2Output : {'gfg': [9, 4, 5, 3], 'is': [1, 2, 3, 4, 3, 2], 'best': [2, 2, 2, 3, 4]}Explanation : 2 removed
    9 min read
    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
    Python - Remove K valued key from Nested Dictionary
    Sometimes, while working with records, we can have a problem in which we need to perform the removal of a key from nested dictionary whose value us specific to K. This is a common problem and has its application in data domains such as web development. Lets discuss certain ways in which this task can be performed. Input : test_dict = {'CS': {'price
    8 min read
    Python - Remove dictionary if given key's value is N
    Given list of dictionaries, remove dictionary whose Key K is N. Input : test_list = [{"Gfg" : 3, "is" : 7, "Best" : 8}, {"Gfg" : 9, "is" : 2, "Best" : 9}, {"Gfg" : 5, "is" : 4, "Best" : 10}, {"Gfg" : 3, "is" : 6, "Best" : 15}], K = "Gfg", N = 9 Output : [{"Gfg" : 3, "is" : 7, "Best" : 8}, {"Gfg" : 5, "is" : 4, "Best" : 10}, {"Gfg" : 3, "is" : 6, "B
    5 min read
    Python - Remove Kth key from dictionary
    Many times, while working with Python, we can have a situation in which we require to remove the Kth key of the dictionary. This is useful for Python version 3.8 +, where key ordering is similar to the insertion order. Let’s discuss certain ways in which this task can be performed. Examples: Input : test_dict = {"Gfg" : 20, "is" : 36, "best" : 100,
    6 min read
    Remove Dictionary from List If Key is Equal to Value in Python
    Removing dictionaries from a list based on a specific condition is a common task in Python programming. This operation is useful when working with data represented as a list of dictionaries, and it allows for a more streamlined and refined dataset. In this article, we will explore three concise methods to achieve this task using Python Example: Inp
    3 min read