Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to append to a dictionary in Python

Introduction

In this tutorial, we will learn how to append to a dictionary in Python. We will start by understanding what a dictionary is and how it differs from other data structures in Python. Then, we will discuss different methods to append to a dictionary. All along, we will provide real code examples, intuitions, and analogies to help you understand the concepts better.

If you are new to programming or Python, don't worry. We will try to keep things simple and avoid using jargons. If we have to use any technical terms, we will make sure to explain them clearly.

What is a Dictionary?

In Python, a dictionary is a mutable, unordered collection of key-value pairs, where each key must be unique. Mutable means that we can change the contents of a dictionary after it is created. Unordered means that the elements in the dictionary have no specific order.

To give you an analogy, you can think of a dictionary as a physical dictionary (the book), where each word (the key) has a corresponding definition (the value). Just like you can't have two identical words with different meanings in a physical dictionary, you can't have duplicate keys in a Python dictionary.

Creating a Dictionary

Before we learn how to append to a dictionary, let's see how to create one. There are multiple ways to create a dictionary in Python. The most common way is to use curly braces {} and separate the keys and values with a colon :. Here's an example:

# Creating a dictionary with three key-value pairs
person = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

# Printing the dictionary
print(person)

Output:

{'name': 'Alice', 'age': 30, 'city': 'New York'}

Appending to a Dictionary

Appending to a dictionary means adding a new key-value pair to the dictionary. There are several ways to append to a dictionary in Python. We will discuss three popular methods in this tutorial:

  1. Using the square bracket notation []
  2. Using the update() method
  3. Using dictionary unpacking

Method 1: Using the Square Bracket Notation

The easiest way to append to a dictionary is by using the square bracket notation. You simply assign a value to a new key, and Python will automatically add the key-value pair to the dictionary. Here's an example:

# Appending a new key-value pair to the dictionary
person["country"] = "USA"

# Printing the updated dictionary
print(person)

Output:

{'name': 'Alice', 'age': 30, 'city': 'New York', 'country': 'USA'}

This method is simple and efficient. However, if you want to add multiple key-value pairs at once or merge two dictionaries, you might prefer one of the other methods.

Method 2: Using the update() Method

The update() method allows you to append one or more key-value pairs to a dictionary. You can pass the new key-value pairs as a dictionary, an iterable (e.g., a list of tuples), or keyword arguments.

Here's an example of appending a single key-value pair using the update() method:

# Appending a new key-value pair to the dictionary
person.update({"job": "Software Engineer"})

# Printing the updated dictionary
print(person)

Output:

{'name': 'Alice', 'age': 30, 'city': 'New York', 'country': 'USA', 'job': 'Software Engineer'}

You can also append multiple key-value pairs at once using the update() method. Here's an example:

# Appending multiple key-value pairs to the dictionary
person.update({"email": "alice@example.com", "phone": "555-1234"})

# Printing the updated dictionary
print(person)

Output:

{'name': 'Alice', 'age': 30, 'city': 'New York', 'country': 'USA', 'job': 'Software Engineer', 'email': 'alice@example.com', 'phone': '555-1234'}

Method 3: Using Dictionary Unpacking

Dictionary unpacking is a technique introduced in Python 3.5, which allows you to merge two dictionaries into a new one using the double asterisk ** operator. This can be useful if you want to append key-value pairs from one dictionary to another without modifying the original dictionaries.

Here's an example of appending key-value pairs from one dictionary to another using dictionary unpacking:

# Creating a second dictionary with some key-value pairs
extra_info = {
    "hobbies": ["reading", "traveling"],
    "fav_color": "blue"
}

# Appending the key-value pairs from the second dictionary to the first
merged_person = {**person, **extra_info}

# Printing the updated dictionary
print(merged_person)

Output:

{'name': 'Alice', 'age': 30, 'city': 'New York', 'country': 'USA', 'job': 'Software Engineer', 'email': 'alice@example.com', 'phone': '555-1234', 'hobbies': ['reading', 'traveling'], 'fav_color': 'blue'}

Note that this method creates a new dictionary and doesn't modify the original dictionaries. If you want to update the original dictionary in-place, you should use the update() method instead.

Conclusion

In this tutorial, we have learned how to append to a dictionary in Python using three different methods:

  1. Using the square bracket notation []
  2. Using the update() method
  3. Using dictionary unpacking

You can choose the method that best suits your needs depending on whether you want to append a single key-value pair, multiple key-value pairs, or merge two dictionaries.

We hope this tutorial has helped you understand how to work with dictionaries in Python. Remember to keep practicing and experimenting with different methods to become more confident in using dictionaries. Happy coding!