Skip to content

Remove key from dictionary Python | Example code

  • by

Using the del keyword or pop() function can Remove the key from the dictionary Python.

del my_dict['key']

OR

my_dict.pop('key', None)

Example Remove key from dictionary Python

Simple example code.

Using del keyword

To delete a key regardless of whether it is in the dictionary, use the two-argument form of dict.pop():

This will return my_dict[key] if key exists in the dictionary, and None otherwise. If the second parameter is not specified (i.e. my_dict.pop('key')) and key does not exist, a KeyError is raised.

Deleting the ‘D’ key.

dic1 = {'A': 1, 'B': 5, 'C': 10, 'D': 15}

del dic1['D']

print(dic1)

Output:

Remove key from dictionary Python

Using pop() function

To delete a key that is guaranteed to exist use it. This will raise a KeyError if the key is not in the dictionary.

dic1 = {'A': 1, 'B': 5, 'C': 10, 'D': 15}

dic1.pop('D', None)

print(dic1)

Output: {‘A’: 1, ‘B’: 5, ‘C’: 10}

How to remove multiple keys from the dictionary?

Answer: Use a for-loop to iterate through a list of keys to remove. At each iteration, use the syntax del dict[key] to remove key from dict.

Same you can use dict.pop(k) to remove the current key k from dict.

dic1 = {'A': 1, 'B': 5, 'C': 10, 'D': 15}

remove = ["A", "B"]

for key in remove:
    del dic1[key]

print(dic1)

Output: {‘C’: 10, ‘D’: 15}

Do comment if you have any doubts or suggestions on this Python dictionary code.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading