Append to Dictionary in Python

This article will discuss how to add or append new key-value pairs to a dictionary or update existing keys’ values.

Table of Contents

We can add/append key-value pairs to a dictionary in python either by using the [] operator or the update function. Let’s first have an overview of the update() function,

Overview of dict.update()

Python dictionary provides a member function update() to add a new key-value pair to the diction or to update the value of a key i.e.

dict.update(sequence)

Parameters:

  • sequence: An iterable sequence of key-value pairs.
    • It can be a list of tuples or another dictionary of key-value pairs.

Returns:

  • It returns None

For each key-value pair in the sequence, it will add the given key-value pair in the dictionary and if key already exists, it will update its value. We can use this function to add new key-value pairs in the dictionary or updating the existing ones.

Checkout complete tutorial on dict.update() function.

Let’s see some examples,

Add / Append a new key-value pair to a dictionary in Python

We can add a new key-value pair to a dictionary either using the update() function or [] operator. Let’s look at them one by one,

Add / Append a new key value pair to a dictionary using update() function

To add a new key-value in the dictionary, we can wrap the pair in a new dictionary and pass it to the update() function as an argument,

# Dictionary of strings and ints
word_freq = {
"Hello": 56,
"at": 23,
"test": 43,
"this": 43
}

# Adding a new key value pair
word_freq.update({'before': 23})

print(word_freq)

Output

{'Hello': 56,
 'at': 23,
 'test': 43,
 'this': 43,
 'before': 23}

It added the new key-value pair in the dictionary. If the key already existed in the dictionary, then it would have updated its value.
If the key is a string you can directly add without curly braces i.e.

# Adding a new key value pair
word_freq.update(after=10)

Output:

{'Hello': 56,
 'at': 23,
 'test': 43,
 'this': 43,
 'before': 23,
 'after': 10}

Add / Append a new key-value pair to a dictionary using [] operator

We add a new key and value to the dictionary by passing the key in the subscript operator ( [] ) and then assigning value to it. For example,

# Dictionary of strings and ints
word_freq = {
    "Hello": 56,
    "at": 23,
    "test": 43,
    "this": 43
}


# Add new key and value pair to dictionary
word_freq['how'] = 9

print(word_freq)

Output:

{'Hello': 56,
 'at': 23,
 'test': 43,
 'this': 43,
 'how': 9}

It added a new key ‘how’ to the dictionary with value 9.

Add to python dictionary if key does not exist

Both the subscript operator [] and update() function works in the same way. If the key already exists in the dictionary, then these will update its value. But sometimes we don’t want to update the value of an existing key. We want to add a new key-value pair to the dictionary, only if the key does not exist.

We have created a function that will add the key-value pair to the dictionary only if the key does not exist in the dictionary. Check out this example,

def add_if_key_not_exist(dict_obj, key, value):
    """ Add new key-value pair to dictionary only if
    key does not exist in dictionary. """
    if key not in dict_obj:
        word_freq.update({key: value})

# Dictionary of strings and ints
word_freq = {"Hello": 56,
             "at": 23,
             "test": 43,
             "this": 43}

add_if_key_not_exist(word_freq, 'at', 20)

print(word_freq)

Output:

{'Hello': 56,
 'at': 23,
 'test': 43,
 'this': 43}

As key ‘at’ already exists in the dictionary, therefore this function did not added the key-value pair to the dictionary,

Now let’s call this function with a new pair,

add_if_key_not_exist(word_freq, 'how', 23)

print(word_freq)

Output:

{'Hello': 56,
 'at': 23,
 'test': 43,
 'this': 43,
 'how': 23}

As key ‘how’ was not present in the dictionary, so this function added the key-value pair to the dictionary.

Add / Append values to an existing key to a dictionary in python

Suppose you don’t want to replace the value of an existing key in the dictionary. Instead, we want to append a new value to the current values of a key. Let’s see how to do that,

def append_value(dict_obj, key, value):
    # Check if key exist in dict or not
    if key in dict_obj:
        # Key exist in dict.
        # Check if type of value of key is list or not
        if not isinstance(dict_obj[key], list):
            # If type is not list then make it list
            dict_obj[key] = [dict_obj[key]]
        # Append the value in list
        dict_obj[key].append(value)
    else:
        # As key is not in dict,
        # so, add key-value pair
        dict_obj[key] = value

# Dictionary of strings and ints
word_freq = {"Hello": 56,
             "at": 23,
             "test": 43,
             "this": 43}

append_value(word_freq, 'at', 21)

print(word_freq)

Output:

{'Hello': 56,
 'at': [23, 21],
 'test': 43,
 'this': 43}

It added a new value, 21, to the existing values of key ‘at’.

How did it work?

We will check if the key already exists in the dictionary or not,

  • If the key does not exist, then add the new key-value pair.
  • If the key already exists, then check if its value is of type list or not,
    • If its value is list object and then add new value to it.
    • If the existing value is not a list, then add the current value to a new list and then append the new value to the list. Then replace the value of the existing key with the new list.

Let’s check out some other examples of appending a new value to the existing values of a key in a dictionary,

Example 1:

append_value(word_freq, 'at', 22)

print(word_freq)

Output:

{'Hello': 56,
 'at': [23, 21, 22],
 'test': 43,
 'this': 43}

Example 2:

append_value(word_freq, 'how', 33)

print(word_freq)

Output:

{'Hello': 56,
 'at': [23, 21, 22],
 'test': 43,
 'this': 43,
 'how': 33}

Updating the value of existing key in a dictionary

If we call the update() function with a key/value and key already exists in the dictionary, then its value will be updated by the new value, i.e., Key ‘Hello’ already exist in the dictionary,

# Dictionary of strings and ints
word_freq = {"Hello": 56,
             "at": 23,
             "test": 43,
             "this": 43}


# Updating existing key's value
word_freq.update({'Hello': 99})

print(word_freq)

Output:

{'Hello': 99,
 'at': 23,
 'test': 43,
 'this': 43}

The value of the key ‘hello’ is updated to 99.

Check out another example,

word_freq['Hello'] = 101

print(word_freq)

Output:

{'Hello': 101,
 'at': 23,
 'test': 43,
 'this': 43}

Append multiple key value pair in dictionary

As update() accepts an iterable sequence of key-value pairs, so we can pass a dictionary or list of tuples of new key-value pairs to update(). It will all add the given key-value pairs in the dictionary; if any key already exists then, it will update its value.

Adding a list of tuples (key-value pairs) in the dictionary

# Dictionary of strings and ints
word_freq = {"Hello": 56,
             "at": 23,
             "test": 43,
             "this": 43}

# List of tuples
new_pairs = [ ('where', 4) , ('who', 5) , ('why', 6) , ('before' , 20)]

word_freq.update(new_pairs)

print(word_freq)

Output:

{'Hello': 56,
 'at': 23,
 'test': 43,
 'this': 43,
 'where': 4,
 'who': 5,
 'why': 6,
 'before': 20}

Adding a dictionary to another dictionary

Suppose we have two dictionaries dict1 and dict2. Let’s add the contents of dict2 in dict1 i.e.

# Two dictionaries
dict1 = {
    "Hello": 56,
    "at": 23,
    "test": 43,
    "this": 43
}
dict2 = {'where': 4,
         'who': 5,
         'why': 6,
         'this': 20
         }

# Adding elements from dict2 to dict1
dict1.update( dict2 )

print(dict1)

Output:

{'Hello': 56,
 'at': 23,
 'test': 43,
 'this': 20,
 'where': 4,
 'who': 5,
 'why': 6}

Add items to a dictionary in a loop

Suppose we have a list of keys, and we want to add these keys to the dictionary with value 1 to n. We can do that by adding items to a dictionary in a loop,

word_freq = {"Hello": 56,
             "at": 23,
             "test": 43,
             "this": 43}

new_keys = ['how', 'why', 'what', 'where']

i = 1
for key in new_keys:
    word_freq[key] = i
    i += 1

print(word_freq)

Output:

{'Hello': 56,
 'at': 23,
 'test': 43,
 'this': 43,
 'how': 1,
 'why': 2,
 'what': 3,
 'where': 4}

Add list as a value to a dictionary in python

You can add a list as a value to a key in the dictionary,

word_freq = {"Hello": 56,
             "at": 23,
             "test": 43,
             "this": 43}

word_freq.update({'why': [1,2,3]})

print(word_freq)

word_freq['what'] = [1, 2, 3]

print(word_freq)

Output:

{'Hello': 56, 'at': 23, 'test': 43, 'this': 43, 'why': [1, 2, 3]}
{'Hello': 56, 'at': 23, 'test': 43, 'this': 43, 'why': [1, 2, 3], 'what': [1, 2, 3]}

Learn More,

Summary:

We can add / append new key-value pairs to a dictionary using update() function and [] operator. We can also append new values to existing values for a key or replace the values of existing keys using the same subscript operator and update() function.

6 thoughts on “Append to Dictionary in Python”

  1. Pingback: What is a dictionary in python and why do we need it? – thispointer.com

Leave a Reply to A passerby Cancel Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top