Python (Scripting) - Rename a key in a dictionary
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/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