Search code snippets, questions, articles...

Remove a key from a dictionary Python

In this post, you will learn to delete a key from a dictionary in Python. We will be using the del statment for that and other methods that can be helpful in removing a key-value pair from the dictionary.
my_score = {
    "math": 90,
    "physics": 80,
    "chemistry": 85,
    "english": 91
}
#TO REMOVE 'physics' kEY from my_score
del my_score['physics']
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

Output

{'math': 90, 'chemistry': 85, 'english': 91}

Remove a key from a dictionary using the del statement

To delete a key from a dictionary in python you can use the del statment before the dictionary variable name.

Syntax

dict['key_name']

Code example

user_info = {
  'id': 2546,
  'name': 'Mohit',
  'country': 'India',
  'city': 'Delhi'
}

del user_info['country']

print(user_info)

Output

{'id': 2546, 'name': 'Mohit', 'city': 'Delhi'}

Search Index Data (The code snippet can also be found with below search text)

delete a key from dict python
Was this helpful?
0 Comments