Python (Scripting) - Remove keys from a dictionary using del

by
Jeremy Canfield |
Updated: March 18 2024
| Python (Scripting) articles
Let's say you have the following dictionary that contains key value pairs.
Here is how you can remove a key (and it's child keys and values) from a dictionary using del.
#!/usr/bin/python3
dictionary = {
'domains': {
'foo.example.com': {
'alias': 'foo',
'region': 'us-east-1'},
'bar.example.com': {
'alias': 'bar',
'region': 'us-east-1'}
}
}
print (f"before = {dictionary}")
del dictionary['domains']['foo.example.com']
print (f"after = {dictionary}")
Which should return the following.
before = {'domains': {'foo.example.com': {'alias': 'foo', 'region': 'us-east-1'}, 'bar.example.com': {'alias': 'bar', 'region': 'us-east-1'}}}
after = {'domains': {'bar.example.com': {'alias': 'bar', 'region': 'us-east-1'}}}
Let's say you have a list that contains two (or more) dictionaries. Here is how you can remove specific dictionaries.
my_list = [ {"name": "john.doe", "department": "it"}, {"name": "jane.doe", "department": "sales"}, {"name": "jack.doe", "department": "hr"} ]
print("")
print("BEFORE")
indexes_to_remove = []
for index in range(len(my_list)):
print(f"index {index}: {my_list[index]}")
if my_list[index]['name'] == "jane.doe":
indexes_to_remove.append(index)
for index in indexes_to_remove:
print(f"index to remove = {index}")
del my_list[index]
print("")
print("AFTER")
for index in range(len(my_list)):
print(f"index {index}: {my_list[index]}")
Which should return the following.
BEFORE
index 0: {'name': 'john.doe', 'department': 'it'}
index 1: {'name': 'jane.doe', 'department': 'sales'}
index 2: {'name': 'jack.doe', 'department': 'hr'}
index to remove = 1
AFTER
index 0: {'name': 'john.doe', 'department': 'it'}
index 1: {'name': 'jack.doe', 'department': 'hr'}
Did you find this article helpful?
If so, consider buying me a coffee over at