How to remove a key in a dictionary in python ?

Active May 18, 2021    /    Viewed 623    /    Comments 0    /    Edit


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


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount