Python | Ways to remove a key from dictionary - GeeksforGeeks (2024)

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 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()

Python
# 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.

Python
# 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.

Python
# 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.

Python
# 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.

Python
# 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.

Python
# 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 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 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 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}


    manjeet_04

    Python | Ways to remove a key from dictionary - GeeksforGeeks (2)

    Improve

    Previous Article

    Python - Words Frequency in String Shorthands

    Next Article

    Python | Merging two Dictionaries

    Please Login to comment...

    Python | Ways to remove a key from dictionary - GeeksforGeeks (2024)
    Top Articles
    Is It Too Late to Buy Nvidia Stock? | The Motley Fool
    Bring Goods Across the Border
    Is Paige Vanzant Related To Ronnie Van Zant
    Belle Meade Barbershop | Uncle Classic Barbershop | Nashville Barbers
    Emmalangevin Fanhouse Leak
    Espn Expert Picks Week 2
    Does Publix Have Sephora Gift Cards
    TS-Optics ToupTek Color Astro Camera 2600CP Sony IMX571 Sensor D=28.3 mm-TS2600CP
    Chastity Brainwash
    Jinx Chapter 24: Release Date, Spoilers & Where To Read - OtakuKart
    Dumb Money, la recensione: Paul Dano e quel film biografico sul caso GameStop
    Directions To Advance Auto
    Moving Sales Craigslist
    Dallas Craigslist Org Dallas
    Dover Nh Power Outage
    The Blind Showtimes Near Amc Merchants Crossing 16
    Keci News
    Plaza Bonita Sycuan Bus Schedule
    Rs3 Ushabti
    Weve Got You Surrounded Meme
    Busted Mugshots Paducah Ky
    manhattan cars & trucks - by owner - craigslist
    Craigslist Efficiency For Rent Hialeah
    Taylored Services Hardeeville Sc
    Jail Roster Independence Ks
    Noaa Marine Forecast Florida By Zone
    Planned re-opening of Interchange welcomed - but questions still remain
    Duke Energy Anderson Operations Center
    Rund um die SIM-Karte | ALDI TALK
    Melissa N. Comics
    Palmadise Rv Lot
    Rust Belt Revival Auctions
    Mgm Virtual Roster Login
    Rise Meadville Reviews
    Drabcoplex Fishing Lure
    Xemu Vs Cxbx
    Agematch Com Member Login
    Synchrony Manage Account
    Usf Football Wiki
    Michael Jordan: A timeline of the NBA legend
    B.C. lightkeepers' jobs in jeopardy as coast guard plans to automate 2 stations
    Wunderground Orlando
    SF bay area cars & trucks "chevrolet 50" - craigslist
    Weather In Allentown-Bethlehem-Easton Metropolitan Area 10 Days
    The power of the NFL, its data, and the shift to CTV
    Sofia Franklyn Leaks
    Penny Paws San Antonio Photos
    Yourcuteelena
    News & Events | Pi Recordings
    Bedbathandbeyond Flemington Nj
    17 of the best things to do in Bozeman, Montana
    91 East Freeway Accident Today 2022
    Latest Posts
    Article information

    Author: Frankie Dare

    Last Updated:

    Views: 6216

    Rating: 4.2 / 5 (53 voted)

    Reviews: 92% of readers found this page helpful

    Author information

    Name: Frankie Dare

    Birthday: 2000-01-27

    Address: Suite 313 45115 Caridad Freeway, Port Barabaraville, MS 66713

    Phone: +3769542039359

    Job: Sales Manager

    Hobby: Baton twirling, Stand-up comedy, Leather crafting, Rugby, tabletop games, Jigsaw puzzles, Air sports

    Introduction: My name is Frankie Dare, I am a funny, beautiful, proud, fair, pleasant, cheerful, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.