Python (Scripting) - Remove keys from a dictionary using pop
by
Jeremy Canfield |
Updated: March 18 2024
| Python (Scripting) articles
Here is an example of how you can create a dictionary that contains keys and values.
#!/usr/bin/python
dictionary = {
"foo": "Hello",
"bar": "World"
}
print(dictionary)
Which should print the following.
{'foo': 'Hello', 'bar': 'World'}
Here is how you can remove the foo key (and it's value) using pop.
#!/usr/bin/python3
dictionary = {
"foo": "Hello",
"bar": "World"
}
dictionary.pop('foo')
print(dictionary)
Which should now print the following.
{'bar': 'World'}
And here is how you could remove a key and every key and value at and below the key.
#!/usr/bin/python3
dictionary = {
'domains': {
'foo.example.com': {
'alias': 'foo',
'region': 'us-east-1'},
'bar.example.com': {
'alias': 'bar',
'region': 'us-east-1'}
}
}
dictionary['domains'].pop('foo.example.com')
print(dictionary)
Did you find this article helpful?
If so, consider buying me a coffee over at