{"id":3420,"date":"2023-10-22T15:52:59","date_gmt":"2023-10-22T10:22:59","guid":{"rendered":"https:\/\/python-programs.com\/?p=3420"},"modified":"2023-11-10T11:54:49","modified_gmt":"2023-11-10T06:24:49","slug":"remove-a-key-from-dictionary-in-python-del-vs-dict-pop-vs-comprehension","status":"publish","type":"post","link":"https:\/\/python-programs.com\/remove-a-key-from-dictionary-in-python-del-vs-dict-pop-vs-comprehension\/","title":{"rendered":"Remove a key from Dictionary in Python | del vs dict.pop() vs comprehension"},"content":{"rendered":"
As we know, Dictionary plays an important role in python data structure.<\/p>\n
Syntax : mydict = {key1: value1, key2: value2}<\/pre>\nIn this article, we will discuss about different ways to remove a key from dictionary in python.<\/p>\n
Let us assume we have a dictionary with correspondent keys and values:<\/p>\n
#dictionary with keys with their correspondent values\r\ntest_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}<\/pre>\nNow we will see different method to delete an key from dictionary :<\/p>\n
Method -1 : Using dict.pop( ) method :<\/h3>\n
This
pop()<\/code> method is used to delete a key and its value in its place. The advantage over using del is that it provides a mechanism to print the desired value if you try to remove a non-existent spelling. Secondly it also returns the value of the key that is removed as well as performs a simple delete operation.<\/p>\n
#Program :\r\n\r\n#dictionary test_dict\r\ntest_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}\r\n#this key will be deleted\r\nkey_to_be_deleted = 'Sagar'\r\n# As 'Sagar' key is present in dictionary, so pop() will delete\r\n# its entry and return its value\r\nresult = test_dict.pop(key_to_be_deleted, None)\r\nprint(\"Deleted item's value = \", result)\r\nprint(\"Updated Dictionary :\", test_dict)\r\n<\/pre>\nOutput\r\nDeleted item's value = 36\r\nUpdated Dictionary : {'Ram': 32, 'Dhruv': 45}<\/pre>\nIn case the key does not exist :<\/strong><\/p>\n
We use try\/except method to avoid error. We know key
\u2018Soni\u2019<\/code> is not in dictionary. So, an error will generate. To avoid error try\/except method will be used.<\/p>\n
#Program :\r\n\r\n#dictionary test_dict\r\ntest_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}\r\n\r\n#Deleting key which does not exist i.e Soni\r\nkey_to_be_deleted = 'Soni'\r\ntry:\r\n test_dict.pop(key_to_be_deleted)\r\nexcept KeyError:\r\n print('That Key is not in the dictionary')<\/pre>\nOutput :\r\nThat is not present in the dictionary<\/pre>\nMethod-2 : Using items() & for loop :<\/h3>\n
By using
item() method<\/code> and
for loop<\/code> we will iterate over the dictionary. When the key that will be deleted will be matched then delete that key.<\/p>\n
Let’s see a program how it’s implemented.<\/p>\n
#Program :\r\n\r\n# Dictionary with keys and values\r\ntest_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}\r\n# key that to be deleted\r\nkey_to_be_deleted = 'Dhruv'\r\nnew_dict = {}\r\n#using for loop \r\n#Iterate one by one key#If found that key then delete\r\nfor key, value in test_dict.items():\r\n if key is not key_to_be_deleted:\r\n new_dict[key] = value\r\ntest_dict = new_dict\r\nprint(test_dict)\r\n<\/pre>\nOutput\r\n{'Ram': 32, 'Dhruv': 45}<\/pre>\nHere for deletion we used for loop and We created a new temporary dictionary and then duplicated it for all key-value pairs in the original dictionary. During iteration, we copy the key and value pair into a new temporary dictionary only if the key is not equal to the key to be deleted. Once the duplication finished, we copied the contents of the new temporary dictionary into the original dictionary.<\/p>\n
Method-3: Using items() & Dictionary Comprehension :<\/h3>\n
Utilizing the logic of the above example we use items() & dictionary comprehension.<\/p>\n
#Program :\r\n\r\n# Dictionary with keys and values\r\ntest_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}\r\n# key that to be deleted\r\nkey_to_be_deleted = 'Ram'\r\ntest_dict = {key: value for key, value\\\r\n in test_dict.items()\\\r\n if key is not key_to_be_deleted}\r\nprint(test_dict)<\/pre>\nOutput:\r\n{'Ram': 32, 'Dhruv': 45}<\/pre>\nMethod-4: Using del keyword :<\/h3>\n
We can use the
del statement<\/code> to delete a key-value pair from the dictionary regarding on the key.<\/p>\n
Syntax : del dict[key]<\/pre>\nLet’s use it-<\/p>\n
#Program :\r\n\r\n# Dictionary of keys &values\r\ntest_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}\r\n# Deleting an item from dictionary using del\r\ndel test_dict['Dhruv']\r\nprint(test_dict)<\/pre>\nOutput:\r\n{'Sagar': 36, 'Ram':32}<\/pre>\nIn case the key does not exist :<\/strong>
\nSuppose we want to delete key'Soni'<\/code>, which does not exist then we can use
try-except<\/code> to avoid any exception.<\/p>\n
Let’s see the implementation of it.<\/p>\n
#Program :\r\n\r\n# Dictionary of keys &values\r\ntest_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}\r\n# If key exist in dictionary then delete it using del.\r\nkey_to_be_deleted = 'Soni'\r\ntry:\r\n del test_dict[key_to_be_deleted]\r\nexcept KeyError:\r\n print('That key is not present in the dictionary')<\/pre>\nOutput:\r\nThat key is not present in the dictionary<\/pre>\n","protected":false},"excerpt":{"rendered":"How to remove a key from dictionary using del vs dict.pop() vs comprehension in python ? As we know, Dictionary plays an important role in python data structure. The elements are written with in { }curly brackets, having keys and values. Each key-value pair mapped with the key to its related value. In Dictionaries duplicates …<\/p>\n