How to remove a key from a dictionary in python

0

To remove a key from a dictionary we can use the pop() function. You can pass the key that you want to delete to the pop function and it will delete that key from the python dictionary.


my_dict.pop('key')

Similarly, you can use python del keyword to remove a key from a dictionary in python. both will work perfectly to remove a key or entry from a python dictionary.


del my_dict['key']

remove a key from dict

Remove a key from a Dictionary:-

You can remove a key from a dictionary using the following methods. Removing a key will means you are removing the whole entries from a dictionary. A dictionary is comprised of key and value pair. So if you remove a key then the value will no longer be available.

  • remove a key from a dictionary using the pop() function
  • remove a key from a dictionary using the del keyword in python

Remove a key from a dictionary using pop() function in python

This is the safest way to delete a key from a dictionary. If you are not sure that there is a key and you want to delete them, you can use the second argument with the key to the pop() function.


my_dict.pop('key', None)

Remove a Key from a dictionary using the del keyword in python

Another way you can delete a key from the dictionary is to use the del keyword in python. To delete a key that is guaranteed to exist, you can also use:


del my_dict['key']

This will raise a KeyError if the key is not in the dictionary. so to make sure the key exists we can check it before we actually try to dlete the key.


if 'key' in my_dict: 
	del my_dict['key']

Or to do it more professionaly using try, except block in python. we can do it as follow.


try:
    del my_dict['key']
except KeyError:
    pass

What is the fastest way to remove a key from a dictionary

If we use timeit module in python to time the execution. it turns out that the fastest way is to use the del keyword instead of the pop() funciton.


>>> import timeit
>>> setup = "d = {i: i for i in range(100000)}"

>>> timeit.timeit("del d[3]", setup=setup, number=1)
1.79e-06
>>> timeit.timeit("d.pop(3)", setup=setup, number=1)
2.09e-06
>>> timeit.timeit("d2 = {key: val for key, val in d.items() if key != 3}", setup=setup, number=1)
0.00786

Summary and conclusion

We have discussed two different methods that can be used to delete a key from a dictionary in python. If you have any questions, please make sure you leave them in the comment section.

Post a Comment

0Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !