Bootstrap FreeKB - Python (Scripting) - Rename a key in a dictionary
Python (Scripting) - Rename a key in a dictionary

Updated:   |  Python (Scripting) articles

Here is an example of how you can create a dictionary that contains keys and values.

#!/usr/bin/python3
dictionary = {
  "foo": "Hello",
  "bar": "World"
}
print(dictionary)

 

Which should print the following.

{'foo': 'Hello', 'bar': 'World'}

 

Here is how you could rename the "foo" key to "test".

#!/usr/bin/python3
dictionary = {
  "foo": "Hello",
  "bar": "World"
}

dictionary['test'] = dictionary.pop('foo')

print(dictionary)

 

Which should now print the following. Notice that the order of the keys in the dictionary did not survive the pop. This is because pop appends to the end of a dictionary.

{'bar': 'World', 'test': 'Hello'}

 

And here is how you could rename a key in a nested dictionary. In this example, the foo.example.com key is renamed to test.example.com.

#!/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']['test.example.com'] = 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 2e0c5c in the box below so that we can be sure you are a human.