python
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']
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'}
Was this helpful?
Similar Posts
- Check if a key exist in a dictionary Python
- Delete a key value pair from a dictionary in Python
- Get Key from a Dictionary using Value in Python
- Remove dictionary from a list in Python
- Get all values by key name from a list of dictionaries Python
- Django send post request with different field than primary key.
- [Python] Using comprehension expression to convert list of dictionaries to nested dictionary