Add Item to Dictionary in Python

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 Dictionary

Following is the syntax to add a key:value pair to the dictionary.

Dictionary[newKey] = newValue

Example 1: Add Items to 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

Output

{'a': '65', 'b': '66', 'c': '67', 'd': '68', 'e': '69', 'f': '70'}

Example 2: Add Item to Dictionary – With existing Key value

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

Output

{'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.

Quiz - Let's see if you can answer these questions

Q1: Which of the following statement initializes an empty Dictionary in Python?

Q2: Which of the following statement creates a new key:value pair of "a":256 in this dictionary?