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.
# Initializing dictionarytest_dict = {"Arushi": 22, "Mani": 21, "Haritha": 21}# Printing dictionary before removalprint("The dictionary before performing remove is : ", test_dict)# Using del to remove a dict# removes Manidel test_dict['Mani']# Printing dictionary after removalprint("The dictionary after remove is : ", test_dict)# Using del to remove a dict# raises exceptiondel 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()
# Initializing dictionarytest_dict = {"Arushi": 22, "Anuradha": 21, "Mani": 21, "Haritha": 21}# Printing dictionary before removalprint("The dictionary before performing remove is : " + str(test_dict))# Using pop() to remove a dict. pair# removes Maniremoved_value = test_dict.pop('Mani')# Printing dictionary after removalprint("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_valueremoved_value = test_dict.pop('Manjeet', 'No Key found')# Printing dictionary after removalprint("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 : 21The 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.
# Initializing dictionarytest_dict = {"Arushi": 22, "Anuradha": 21, "Mani": 21, "Haritha": 21}# Printing dictionary before removalprint("The dictionary before performing\remove is : " + str(test_dict))# Using items() + dict comprehension to remove a dict. pair# removes Maninew_dict = {key: val for key, val in test_dict.items() if key != 'Mani'}# Printing dictionary after removalprint("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.
# Initializing dictionarytest_dict = {"Arushi": 22, "Anuradha": 21, "Mani": 21, "Haritha": 21}# Printing dictionary before removalprint("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.
# Initializing dictionarytest_dict = {"Arushi": 22, "Anuradha": 21, "Mani": 21, "Haritha": 21}print(test_dict)# empty the dictionary dy = {}# eliminate the unrequired elementfor key, value in test_dict.items(): if key != 'Arushi': y[key] = valueprint(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.
# Initializing dictionarytest_dict = {"Arushi": 22, "Anuradha": 21, "Mani": 21, "Haritha": 21}print(test_dict)# empty the dictionary ddel test_dicttry: 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.
# Initializing dictionarytest_dict = {"Arushi": 22, "Anuradha": 21, "Mani": 21, "Haritha": 21}print(test_dict)# empty the dictionary dtest_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 thelist()
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 thepop()
method, Python will raise aKeyError
:
- 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 likedel
orpop()
:
- Using
del
statement:import jsonjson_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 jsonjson_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 aKeyError
. Alternatively, usediscard()
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
Python - Words Frequency in String Shorthands
Next Article
Python | Merging two Dictionaries