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)

 

Let's say you have a list that contains two (or more) dictionaries. Here is how you can remove specific dictionaries. In this example, the dictionary with index 0 will be removed from my_list.

my_list = [ {"name": "john.doe", "department": "it"}, {"name": "jane.doe", "department": "sales"}, {"name": "jack.doe", "department": "hr"} ]

my_list.pop(0)

print(my_list)

 

 




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 80961f in the box below so that we can be sure you are a human.