Contents
Python Add Item(s) to Dictionary
To add an item to an existing dictionary, you can assign value to the dictionary variable indexed using the key.
In this tutorial, we shall learn how to add a new key:value pair to a Python Dictionary, with help of some well detailed Python programs.
Syntax to add key:value pair to dict
Following is the syntax to add a key:value pair to the dictionary.
Dictionary[newKey] = newValue
Examples
1. Add three items to given dictionary
In this example, we will create a Python Dictionary with some initial values and then add multiple items to this dictionary.
Python Program
# Create and initialize a dictionary
myDictionary = {
'a': '65',
'b': '66',
'c': '67'
}
# Add new items to the dictionary
myDictionary['d'] = '68'
myDictionary['e'] = '69'
myDictionary['f'] = '70'
# Print dictionary
print(myDictionary)
Run Code CopyOutput
{'a': '65', 'b': '66', 'c': '67', 'd': '68', 'e': '69', 'f': '70'}
2. Try adding an item to dictionary where the key already exists
If you try to add a key:value pair to the dictionary, in which case the dictionary has already that key, the value would be updated.
Python Program
# Create and initialize a dictionary
myDictionary = {
'a': '65',
'b': '66',
'c': '67'
}
# Add new items to the dictionary
myDictionary['c'] = '68'
# Print dictionary
print(myDictionary)
Run Code CopyOutput
{'a': '65', 'b': '66', 'c': '68'}
The key:value pair got update updated. So, you have to make sure, if the key is already present or not, and then try adding the new key:value pair.
Summary
In this tutorial of Python Examples, we learned how to add one or more items to an existing Python Dictionary with the help of well detailed examples.