Saturday, November 16, 2024
Google search engine
HomeGuest BlogsPython: How to Add Items to Dictionary

Python: How to Add Items to Dictionary

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 DictionaryPython: 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 assignmentPython 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 methodPython 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 methodPython 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 copyPython 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 statementPython 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 listPython 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 zipPython 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 tutorials refer to our article and find out how to pretty print a JSON file using Python.

Next, learn how to initialize directory in Python.

Was this article helpful?
YesNo

RELATED ARTICLES

Most Popular

Recent Comments