Python Append to Dictionary

Harsh S.
By
Harsh S.
Hello, I'm Harsh, I hold a degree in Masters of Computer Applications. I have worked in different IT companies as a development lead on many large-scale...
10 Min Read

Dictionaries are a versatile data structure that allows you to store key-value pairs. In this tutorial, we will discuss the different ways to append to a dictionary in Python and provide examples of how to use each method. We will also compare the different methods and advise which one is the most suitable for different situations.

Different Ways to Append to a Dictionary in Python

Appending to a dictionary means adding a new key-value pair to it. However, Python dictionaries don’t have an “append” method like lists do. Instead, we can use various methods to achieve the same result. Let’s explore different ways to append data to a dictionary.

Method 1. Using [] to append to a dictionary

The [] is called the square bracket notation. It is one of the simplest ways to append data to a dictionary. You can directly set the desired value to a new key within the dictionary.

Here’s an example:

# Create an empty dictionary
my_dict = {}

# Append key-value pairs
my_dict['product'] = 'Laptop'
my_dict['price'] = 1200
my_dict['brand'] = 'Dell'

# Resulting dictionary
# {'product': 'Laptop', 'price': 1200, 'brand': 'Dell'}

This method is the simplest and most suitable when you want to append a single key-value pair to an existing dictionary in Python.

You can understand the above example more clearly with the help of the below visual aid.

# Method 1: Square Bracket Notation
# -----------------------------------
# [   ]   [   ]   [   ]   [   ]
#  |     |     |     |     |
#  |     |     |     |     +------> Key: 'product', Value: 'Laptop'
#  |     |     |     +------------> Key: 'price', Value: 1200
#  |     |     +------------------> Key: 'brand', Value: 'Dell'

This visual illustrates how each method affects the structure of the dictionary as data is appended or added. The arrows show the direction of data flow, and the boxes represent the key-value pairs within the dictionary. You can see that each method has a unique way of adding data.

Method 2. Using update() to append to a dictionary

The update() method takes a dictionary or an iterable of key-value pairs as an argument and adds them to the dictionary. If a key already exists in the dictionary, the old value is overwritten with the new one.

It can be especially useful for merging dictionaries. Here is an example of how to use the update() method to append to a dictionary:

# Create two dictionaries
dict1 = {'country': 'Spain'}
dict2 = {'language': 'Spanish', 'currency': 'Euro', 'population': 47000000}

# Append data from dict2 to dict1
dict1.update(dict2)
print(dict1)

# Resulting dictionary
# {'country': 'Spain', 'language': 'Spanish', 'currency': 'Euro', 'population': 47000000}

You can easily grasp the above example with the help of the below visual key.

Method 2: update() Method
-------------------------
# {   }   
#  |     
#  +--> Key: 'country', Value: 'Spain'
#  |
#  +--> Key: 'language', Value: 'Spanish'
#  |
#  +--> Key: 'currency', Value: 'Euro'
#  |
#  +--> Key: 'population', Value: 47000000

This method is useful when you want to add multiple key-value pairs to an existing dictionary.

Method 3. Using the SetDefault() Method

The Python SetDefault() method allows you to append a new key with a default value if it doesn’t already exist in the dictionary. This can be useful when you want to ensure a key is present before appending data. Here’s an example:

# Create a dictionary with an existing key
my_dict = {'fruit': 'Orange'}

# Append new keys with default values
my_dict.setdefault('color', 'Orange')
my_dict.setdefault('taste', 'Sweet')
my_dict.setdefault('vitamin', 'C')

print(my_dict)

# Resulting dictionary
# {'fruit': 'Orange', 'color': 'Orange', 'taste': 'Sweet', 'vitamin': 'C'}

To grasp the above example, take the help of the below visual key.

Method 3: setdefault() Method
------------------------------
# {   }
#  |
#  +--> Key: 'fruit', Value: 'Orange'
#  |
#  +--> Key: 'color', Value: 'Orange'
#  |
#  +--> Key: 'taste', Value: 'Sweet'
#  |
#  +--> Key: 'vitamin', Value: 'C'

This method will come in handy when you want to add a key-value pair conditionally based on whether the key already exists.

Method 4. Using Dictionary Comprehension

Dictionary comprehension is a concise way to create a new dictionary by iterating over an iterable (e.g., a list) and producing key-value pairs. You can use it to append data to a dictionary in Python. Here’s an example:

# Create an empty dictionary
my_dict = {}

# Append data using dictionary comprehension
data = [('animal', 'Tiger'), ('habitat', 'Jungle'), ('sound', 'Roar')]

my_dict = {k: v for k, v in data}
print(my_dict)

# Resulting dictionary
# {'animal': 'Tiger', 'habitat': 'Jungle', 'sound': 'Roar'}

To understand the above code, take the help of the below visual key.

Method 4: Dictionary Comprehension
-----------------------------------
# {   }
#  |
#  +--> Key: 'animal', Value: 'Tiger'
#  |
#  +--> Key: 'habitat', Value: 'Jungle'
#  |
#  +--> Key: 'sound', Value: 'Roar'

This method is suitable when you want to create a new dictionary with appended data.

Method 5. Using a Custom Function

You can create a custom function to append data to a dictionary. This approach allows for more control and customization when adding data. Here’s an example:

# Create an empty dictionary
my_dict = {}

# Custom function to append data
def append_data(dictionary, key, value):
    dictionary[key] = value

# Append data using the custom function
append_data(my_dict, 'sport', 'Soccer')
append_data(my_dict, 'team', 'Manchester United')
append_data(my_dict, 'player', 'Cristiano Ronaldo')

# Resulting dictionary
print(my_dict)

# {'sport': 'Soccer', 'team': 'Manchester United', 'player': 'Cristiano Ronaldo'}

To grasp the above code quickly, go through the below textual visual.

Method 5: Custom Function
--------------------------
# {   }
#  |
#  +--> Key: 'sport', Value: 'Soccer'
#  |
#  +--> Key: 'team', Value: 'Manchester United'
#  |
#  +--> Key: 'player', Value: 'Cristiano Ronaldo'

This method is suitable when you want to hide the logic for adding data in a reusable function.

Method 6. Using Collections DefaultDict()

The collections.defaultdict() is a specialized dictionary container that allows you to provide a default factory function for values. When adding data, if the key doesn’t exist, it will create the key with the default value provided by the factory function.

Code Snippet:

from collections import defaultdict

# Create a defaultdict with a default value of 0 for integer keys
my_dict = defaultdict(int)

# Append data
my_dict['apples'] += 5
my_dict['bananas'] += 3

# Resulting dictionary
# defaultdict(int, {'apples': 5, 'bananas': 3})

Visual Representation:

Method 6: collections.defaultdict()
-------------------------------------
{   }
 | 
 |--> Key: 'apples', Value: 5
 |
 +--> Key: 'bananas', Value: 3

In this example, we create a defaultdict with a default value of 0 for integer keys. When we append data using this method, if the key exists, it increments the existing value; if the key doesn’t exist, it creates the key with the default value.

This method is suitable when you want to work with default values for missing keys and avoid key errors.

Comparison of Methods

Here’s a table comparing the different methods for appending data to a dictionary in Python.

MethodUse CaseProsCons
Square Bracket NotationSingle key-value pairSimplicity, readabilityLimited to adding one pair at a time
update() MethodMultiple key-value pairsMerge dictionaries easilyOverwrites existing values with the same keys
setdefault() MethodConditional appendingSets default values for missing keysCan be less intuitive for some use cases
Dictionary ComprehensionCreate a new dictionaryConcise syntax, versatileRequires creating a new dictionary
Custom FunctionCustom logic for appending dataControl and reusabilityRequires defining a function
collections.defaultdict()Default values for missing keysAvoids key errors, sets default valuesRequires importing the ‘collections’ module
Comparison

Also Read: Search in Dictionary

In summary, the choice of method depends on the complexity of your task and the level of control and customization you require.

MethodBest Use Case
Square Bracket NotationSingle key-value pair
update() MethodMerging dictionaries
setdefault() MethodConditional appending
Dictionary ComprehensionCreating a new dictionary with appended data
Custom FunctionCustom logic and reusability
Use cases

Choose the method that suits your specific needs and coding style, and you’ll be able to efficiently append data to Python dictionaries.

Lastly, our site needs your support to remain free. Share this post on social media (Linkedin/Twitter) if you gained some knowledge from this tutorial.

Enjoy coding,
TechBeamers.

Share This Article