Python: How to Add Items to Dictionary

November 10, 2022

Introduction

Dictionaries are Python's built-in data types for storing key-value pairs. The dictionary elements are changeable and don't allow duplicates. In Python 3.7 and higher, dictionary items are ordered. Lower versions of Python treat dictionary elements as unordered.

Depending on the desired result and given data, there are various ways to add items to a dictionary.

This guide shows how to add items to a Python dictionary through examples.

Python: How To Add Items To A Dictionary

Prerequisites

How to Add an Item to a Dictionary in Python

To test out different methods of adding items to a dictionary, create a dictionary with two items. Use the following code:

my_dictionary = {
  "one": 1,
  "two": 2
}

The methods below show how to add one or multiple items to a Python dictionary.

Note: Adding an item with an existing key replaces the dictionary item with a new value. Make sure to provide unique keys to avoid overwriting data.

Method 1: Using The Assignment Operator

The assignment operator sets a value to a key using the following syntax:

dictionary_name[key] = value

The assignment operator adds a new key-value pair if the key does not exist.

The following code demonstrates how to add an item to a Python dictionary using the assignment operator:

my_dictionary = {
  "one": 1,
  "two": 2
}

print("Before:", my_dictionary)

my_dictionary["tree"] = 3

print("After:", my_dictionary)
Python add item to dictionary assignment

The code outputs the dictionary contents before and after adding a new item.

Method 2: Using update()

The update() method updates an existing dictionary with a new dictionary item:

dictionary_name.update({key:value})

The method accepts one or multiple key-value pairs, which is convenient for adding more than one element.

The example code looks like the following:

my_dictionary = {
  "one": 1,
  "two": 2
}

print("Before:", my_dictionary)

my_dictionary.update({"three":3})

print("After:", my_dictionary)
Python add item to dictionary update method

Use this method to add multiple new items or append a dictionary to an existing one.

Method 3: Using __setitem__

The __setitem__ method is another way to append a new dictionary item:

dictionary_name.__setitem__(key,value)

For example:

my_dictionary = {
  "one": 1,
  "two": 2
}

print("Before:", my_dictionary)

my_dictionary.__setitem__("three", 3)

print("After:", my_dictionary)
Python add item to dictionary setitem method

The method sets the item key as "three" with the value 3.

Method 4: Using The ** Operator

The ** operator helps merge an existing dictionary into a new dictionary and adds additional items. The syntax is:

new_dictionary = {**old_dicitonary, **{key:value}}

For example, to copy an existing dictionary and append a new item to a new one, see the following code:

my_dictionary = {
  "one": 1,
  "two": 2
}

my_new_dictionary = {**my_dictionary, **{"three":3}}

print("Old:", my_dictionary)
print("New:", my_new_dictionary)
Python add item to dictionary copy

The new dictionary contains the added item, preserving the old dictionary values. Use this method to avoid changing existing dictionaries.

Method 5: Checking If A Key Exists

Use an if statement to check whether a key exists before adding a new item to a dictionary. The example syntax is:

if key not in dictionary_name:
    dictionary_name[key] = value

For example:

my_dictionary = {
  "one": 1,
  "two": 2
}

print("Before:", my_dictionary)

if "three" not in my_dictionary:
  my_dictionary["three"] = 3

print("After:", my_dictionary)
Python add item to dictionary if not in statement

The code checks whether a key with the provided name exists before adding the item to the dictionary. If the provided key exists, the existing key value does not update, and the dictionary stays unchanged.

Method 6: Using A For Loop

Add key-value pairs to a nested list and loop through the list to add multiple items to a dictionary. For example:

my_dictionary = {
  "one": 1,
  "two": 2
}

my_list = [["three", 3], ["four", 4]]

print("Before:", my_dictionary)

for key,value in my_list:
    my_dictionary[key] = value

print("After:", my_dictionary)
Python add item to dictionary nested list

The for loop goes through the pairs inside the list and adds two new elements.

Note: For loop and a counter are also used as one of the methods to identify the length of a list. Learn more by visiting our guide How to Find the List Length in Python.

Method 7: Using zip

Use zip to create key-value pairs from two lists. The first list contains keys and the second contains the values.

For example:

my_dictionary = {
  "one": 1,
  "two": 2
}

my_keys = ["three", "four"]
my_values = [3, 4]

print("Before:", my_dictionary)

for key,value in zip(my_keys, my_values):
    my_dictionary[key] = value

print("After:", my_dictionary)
Python add item to dictionary zip

The zip function matches elements from two lists by index, creating key-value pairs.

How to Update a Python Dictionary

Update Python dictionary values using the same syntax as adding a new element. Provide the key name of an existing key, for example:

my_dictionary = {
  "one": 1,
  "two": 2
}

print("Before:", my_dictionary)

my_dictionary["one"] = 3

print("After:", my_dictionary)

Since Python does not allow duplicate entries in a dictionary, the code updates the value for the provided key and overwrites the existing information.

Conclusion

After going through the examples in this tutorial, you know how to add items to a Python dictionary. All methods provide unique functionalities, so choose a way that best suits your program and situation.

For more Python tutorial refer to our article and find out how to pretty print a JSON file using Python.

Was this article helpful?
YesNo
Milica Dancuk
Milica Dancuk is a technical writer at phoenixNAP who is passionate about programming. Her background in Electrical Engineering and Computing combined with her teaching experience give her the ability to easily explain complex technical concepts through her content.
Next you should read
File Handling in Python: Create, Open, Append, Read, Write
February 24, 2022

Working with files is part of everyday tasks in programming. This tutorial teaches you elementary file...
Read more
Handling Missing Data in Python: Causes and Solutions
July 1, 2021

Some machine learning algorithms won't work with missing data. Learn how to discover if your dataset has missing...
Read more
How to Comment in Python
November 25, 2019

The ability to use comments while writing code is an important skill valued among developers. These comments can be used to leave notes about the...
Read more
How to Get the Current Date and Time in Python
August 14, 2019

The article shows you how to create a basic Python script that displays the current date and time. Find out how to use the...
Read more