Update Dictionary in Python
You already know that we can access key:value pairs of a Python Dictionary using key as index with the reference to dictionary. In the same way, you can assign a value to this keyed index to dictionary to update the value of key:value pair in this dictionary.
In this tutorial, we will learn how to Update Dictionary in Python.
Updating a Dictionary in Python can be any of the following.
- Update value in key:value pair of Dictionary
- Add new key:value pair to Dictionary
- Delete key:value pair of Dictionary
We will look into each of the above said scenarios using examples.
Update value in key:value pair of Dictionary
To update value in a Dictionary corresponding to a key, all you have to do is assign the value to the key indexed dictionary reference.
In the following program, we update the value in dictionary myDict for key foo.
Python Program
myDict = {
'foo':12,
'bar':14
}
#update value for key 'foo'
myDict['foo'] = 56
print(myDict)
Run Code CopyOutput
{'foo': 56, 'bar': 14}
Add new key:value pair to Dictionary
To add new key:value pair to a Dictionary, you have to assign the value to the key-indexed dictionary reference.
In the following program, we add a new key:value pair 'moo':85 to the dictionary myDict.
Python Program
myDict = {
'foo':12,
'bar':14
}
#add key:value to dictionary
myDict['moo'] = 85
print(myDict)
Run Code CopyOutput
{'foo': 12, 'bar': 14, 'moo': 85}
Delete key:value pair of Dictionary
To delete key:value pair in a Dictionary, you can use del keyword with dictionary[key] as shown in the following program.
Python Program
myDict = {
'foo':12,
'bar':14,
'moo':85
}
#del key:value pair from dictionary
del myDict['foo']
print(myDict)
Run Code CopyOutput
{'bar': 14, 'moo': 85}
Summary
In this tutorial of Python Examples, we learned how to update Dictionary in Python, with the help of well detailed example programs.