Bootstrap FreeKB - Python (Scripting) - Remove keys from a dictionary using pop
Python (Scripting) - Remove keys from a dictionary using pop

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


Please enter 937b32 in the box below so that we can be sure you are a human.