Summary: In this tutorial, we will learn different ways to append values to an existing key in a dictionary in Python.

Sometimes, we may need to add more values to an existing key in a dictionary, or if the key doesn’t exist then create a new key with the given values.

In Python dictionary, we can append values to a key in 3 easy ways:

  • Using .append with .setdefault()
  • Using .append with collections.defaultdict()
  • Using .append with if and else

Let’s see an example of each of the methods.

Method 1: Using .append with .setdefault()

In this method, we first set an empty list as the default value for the given key by using the setdefault() method of the dictionary (if the key does not exist).

Then, we append the new value to the same by using the append() method.

product = { 'name': 'IPhone Cover X', 'price': '$299', 'reviews': ['Good Quality']}

product.setdefault('reviews', []).append('Very Cheap Cover! Nice')
print(product)

'''
{
    'name': 'IPhone Cover X',
    'price': '$299', 
    'reviews': ['Good Quality', 'Very Cheap Cover! Nice']
}
'''

However, this approach will fail if the key already exists in the dictionary and its corresponding value is not of the type list.

Method 2: Using .append with collections.defaultdict()

In this method, we create a dictionary using the defaultdict() method of the collections module and append value using the append() method.

from collections import defaultdict

#create dictionary using defaultdict
product = defaultdict(list, { 'name': 'Bunk Bed X', 'price': '$699'})

product['reviews'].append('Awesome Bed')
product['reviews'].append('Not Bad')
print(product)

'''
{
    'name': 'Bunk Bed X',
    'price': '$699',
    'reviews': ['Awesome Bed', 'Not Bad']
}
'''

The advantage of creating the dictionary using the defaultdict() is that it automatically creates the item of the specified type (type provided as the first parameter in the defaultdict() method) if the key we are trying to access does not exist.

Unlike the previous method, we don’t need to explicitly initialize every new key with an empty list.

Method 3: Using .append with if and else

In this method, we use the naive approach to append values in the given dictionary.

We check using the if statement whether the given key exists in the dictionary or not.

If not, we first initialize the new key with an empty list in the dictionary and then append the values using the append() method.

user = {'name': 'Pencil Programmer', 'dob': '10/07/1996'}

if 'hobbies' not in user:
    user['hobbies'] = []

user['hobbies'].append('Watching Movies')
user['hobbies'].append('Playing Basketball')

print(user)

'''
{
    'name': 'Pencil Programmer',
    'dob': '10/07/1996',
    'hobbies': ['Watching Movies', 'Playing Basketball']
}
'''

Like the first method, this method assumes that if the key already exists in the dictionary then its value must be of the type list otherwise, it would fail to append values.

Leave a Reply

seven + two =