Add to a Dictionary in Python

If you work with data structures, such as dictionaries, you may wonder whether you can add or append an item the same way as you can do it with a list? Read the rest of the article to find out.

What is a dictionary in Python?

In Python, a dictionary is a collection of key-value pairs separated by a colon. You can access the values by using their corresponding keys. The keys in Python dictionaries are immutable and have to be unique.

fruit = {
    "banana": 4,
    "apple": 12,
    "orange": 7
}

Dict append method

You can add value to a dictionary using the append() function. The added value is going to be a list. You can add a list with a single element or multiple elements.

my_dict = {"fruit": [], "vegetable": []}

my_dict["fruit"].append(['apple', 20])
my_dict["fruit"] = my_dict["fruit"][0]
my_dict["vegetable"].append('onion')

print(my_dict)

The my_dict dictionary contains two keys with empty lists as values. Now, you can use the append() function to add lists to them.

For vegetables, we added a single string element into the list, and for fruit, a list with two elements: string and int. Because we append a list in the case of the fruit dictionary, we get a list of a list as a value.

You can deal with it by getting only the first element of the list.

my_dict["fruit"] = my_dict["fruit"][0]

If you run the code, you’ll get a dictionary with a list as values.

{'fruit': ['apple', 20], 'vegetable': ['onion']}

Using dict update method

A dictionary in Python offers the update() function where you can add the additional element to a dictionary. This code shows how you can do it:

fruit = {
    "banana": 4,
    "apple": 12,
    "orange": 7
}

fruit.update({"pear": 9, "plum": 44})
print(fruit)

The update() function adds two new elements to the fruit dictionary. If you run this code and print out the dictionary, you’ll see that the new values are inside the dictionary. You can update a single, as well as multiple elements to a dictionary.

{'banana': 4, 'apple': 12, 'orange': 7, 'pear': 9, 'plum': 44}

Add or append functions for dictionaries

You can add a new element to a dictionary by assigning value to a new key (dict[key] = new_value).

fruit = {
    "banana": 4,
    "apple": 12,
    "orange": 7
}

print(fruit)
fruit["blueberry"] = 99
print(fruit)

Because there is no “blueberry” inside the dictionary keys, it is added as a new element to the dictionary.

{'banana': 4, 'apple': 12, 'orange': 7}
{'banana': 4, 'apple': 12, 'orange': 7, 'blueberry': 99}

If you try to add a key that is already there, but with a different value, instead of adding a new element, Python is going to update its value.

fruit = {
    "banana": 4,
    "apple": 12,
    "orange": 7
}

fruit["apple"] = 99
print(fruit)

When you run the code, all keys stay the same, only the value for “apple” changed.

{'banana': 4, 'apple': 99, 'orange': 7}

Append another dictionary with a function

Let’s create a function that will use the method from the last example and sum two dictionaries.

fruits = {
    "banana": 4,
    "apple": 12,
    "orange": 7
}

new_fruits = {
    "plum": 34,
    "pear": 11
}

def append(first_dict, second_dict):
    for key in second_dict:
        first_dict[key] = second_dict[key]
        
    return first_dict

fruits = append(fruits, new_fruits)
print(fruits)

This simple function uses the for loop to move through each element of the second dictionary and append it to the first one. The returned value is the sum of both dictionaries.

{'banana': 4, 'apple': 12, 'orange': 7, 'plum': 34, 'pear': 11}

Add or append another dictionary – different approach

There is another approach to the same problem. Instead of adding new values to a dictionary, first, we will append keys of both dictionaries to the keys list and values to the values list. Then we are going to create a new dictionary with all the values from both dictionaries. This is how we can do it:

fruits = {
    "banana": 4,
    "apple": 12,
    "orange": 7
}

new_fruits = {
    "plum": 34,
    "pear": 11
}

def append(first_dict, second_dict):
    keys = []
    values = []

    for key in first_dict:
        keys.append(key)
        values.append(first_dict[key])
    for key in second_dict:
        keys.append(key)
        values.append(second_dict[key])
    new_dict = dict(zip(keys, values))
    return new_dict

fruits = append(fruits, new_fruits)
print(fruits)

Two dictionaries contain the name of fruits and information on how many of them are available. We want to add fruits2 to fruits one using the append function.

First, we are going to create two lists where we can store keys and values.

Then let’s create the first for loop to assign keys to the keys list and the second loop to assign values to the values list.

We are going to create a new dictionary with the values and keys from the lists.

Now, the fruits dictionary contains all the elements.

{'banana': 4, 'apple': 12, 'orange': 7, 'plum': 34, 'pear': 11}

Adding new method to the dictionary class

Although you can’t add new methods to the original dictionary, you can create a subclass that inherits from the dictionary class.

Unfortunately, if you create a new dictionary object without changing its type to MyDict, it will continue to be of the original type and you won’t be able to use our new method.

fruits = {
    "banana": 4,
    "apple": 12,
    "orange": 7
}

new_fruits = {
    "plum": 34,
    "pear": 11
}

class MyDict(dict):
    def append(self, second_dict):
        for key in second_dict:
            self[key] = second_dict[key]

        return self

fruits = MyDict(fruits)

fruits = fruits.append(new_fruits)
print(fruits)

The MyDict class inherits the original dict class. The append method has two parameters: self and dict. The self parameter means that this is a method of the MyDict class. The second parameter takes a dictionary we want to append.

The fruits variable is assigned to itself as a MyDict object.

The last part of the code uses append as a dictionary function.

fruits = fruits.append(new_fruits)

If you run this code, the fruits dictionary will contain elements from both dictionaries.

{'banana': 4, 'apple': 12, 'orange': 7, 'plum': 34, 'pear': 11}

Summary

A dictionary is not a list, so it doesn’t offer functions like add() or append(). What this means, is that you can’t just append or add an item to the end of the dictionary like you would with a list.

Despite this, you can try to use workarounds to simulate this process.