How to remove a key in a dictionary in python ?


Examples of how to remove a key from a dictionary in python:

Create a dictionary in python

Let's first create s dictionary in python

d = {'Age':[27,36,38,87],'Gender':[0,1,1,1],'db_name':'test'}

Note: to check if a dictionary has a given key, a solution is to do:

'Age' in d

returns

True

While

'height' in d

returns

False

Deleting a dictionary key using pop

To remove a key in a dictionary a solution is to use pop()

d = {'Age':[27,36,38,87],'Gender':[0,1,1,1],'db_name':'test'}

d.pop('Gender')

print(d)

gives

{'Age': [27, 36, 38, 87], 'db_name': 'test'}

Note 1: pop() can be use to store the removed key in another dictionary:

d = {'Age':[27,36,38,87],'Gender':[0,1,1,1],'db_name':'test'}

new_d = {}
new_d['Gender'] = d.pop('Gender')

print(d)
print(new_d)

returns

{'Age': [27, 36, 38, 87], 'db_name': 'test'}
{'Gender': [0, 1, 1, 1]}

Note 2: If the key is not in the dictionary, you can add None to avoid a error message:

d.pop('weight', None)

or test first if the key is in the dictionary:

if 'weight' in d:
        d.pop('weight')

Deleting a dictionary key using del

Another solution is to use del:

d = {'Age':[27,36,38,87],'Gender':[0,1,1,1],'db_name':'test'}

del d['Gender']

print(d)

returns

{'Age': [27, 36, 38, 87], 'db_name': 'test'}

Note: It is a option to use pop() if you don't know if the key is or not in the dictionary.

References