Python (Scripting) - Replace values in a dictionary
by
Jeremy Canfield |
Updated: March 20 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 could replace "Hello" with "Goodbye" in the "foo" key.
#!/usr/bin/python3
dictionary = {
"foo": "Hello",
"bar": "World"
}
dictionary['foo'] = "Goodbye"
print(dictionary)
Which should now print the following.
{'foo': 'Goodbye', 'bar': 'World'}
And like this, with nested keys.
#!/usr/bin/python3
dictionary = {
"foo": {
"bar": {
"hello": "world"
}
}
}
print(dictionary)
dictionary['foo']['bar']['hello'] = "Saturn"
print(dictionary)
Did you find this article helpful?
If so, consider buying me a coffee over at