Report this

What is the reason for this report?

How to Add and Update Python Dictionaries Easily

Updated on October 16, 2025
How to Add and Update Python Dictionaries Easily

Introduction

A dictionary is a built-in Python data type. It is a sequence of key-value pairs, where each key is unique and maps to a value. Dictionaries are mutable objects, meaning you can change their content without changing their identity. However, dictionary keys are immutable and need to be unique within each dictionary. This makes dictionaries highly efficient for lookups, insertions, and deletions.

Dictionaries are widely used in Python for various applications such as counting occurrences, grouping data, and storing configurations. Despite their versatility, there’s no built-in add method for dictionaries. Instead, there are several ways to add to and update a dictionary, each with its own use case and advantages.

In this article, you’ll learn different methods to add to and update Python dictionaries. You’ll learn how to use the Python assignment operator, the update() method, and the merge and update dictionary operators. By the end of this tutorial, you’ll have a solid understanding of how to manage and manipulate dictionaries effectively in your Python programs.

Key Takeaways

  • Four Primary Methods: Master the assignment operator (=), update() method, merge operator (|), and update operator (|=) for different use cases
  • Performance Optimization: Use {} instead of dict() for initialization, and choose the right method based on your specific needs
  • Memory Efficiency: The merge operator (|) creates new dictionaries, while update() and |= modify existing ones in-place
  • Python 3.9+ Features: Leverage modern dictionary operators for cleaner, more readable code
  • Best Practices: Understand when to use each method based on performance requirements and code clarity
  • Error Prevention: Learn conditional updates to avoid overwriting existing values when needed

Deploy your Python applications from GitHub using DigitalOcean App Platform. Let DigitalOcean focus on scaling your app.

Four Methods to Add to the Python Dictionary

  1. Using the Assignment Operator
  2. Using the Update Method
  3. Using the Merge Operator
  4. Using the Update Operator

Add to Python Dictionary Using the = Assignment Operator

You can use the = assignment operator to add a new key to a dictionary:

dict[key] = value

If a key already exists in the dictionary, then the assignment operator updates, or overwrites, the value.

The following example demonstrates how to create a new dictionary and then use the assignment operator = to update a value and add key-value pairs:

dict_example = {'a': 1, 'b': 2}

print("original dictionary: ", dict_example)

dict_example['a'] = 100  # existing key, overwrite
dict_example['c'] = 3  # new key, add
dict_example['d'] = 4  # new key, add 

print("updated dictionary: ", dict_example)

The output is:

Output
original dictionary: {'a': 1, 'b': 2} updated dictionary: {'a': 100, 'b': 2, 'c': 3, 'd': 4}

The output shows that the value of a is overwritten by the new value, the value of b is unchanged, and new key-value pairs are added for c and d.

Add to Python Dictionary Without Overwriting Values

Using the = assignment operator overwrites the values of existing keys with the new values. If you know that your program might have duplicate keys, but you don’t want to overwrite the original values, then you can conditionally add values using an if statement.

Continuing with the example from the preceding section, you can use if statements to add only new key-value pairs to the dictionary:

dict_example = {'a': 1, 'b': 2}

print("original dictionary: ", dict_example)

dict_example['a'] = 100  # existing key, overwrite
dict_example['c'] = 3  # new key, add
dict_example['d'] = 4  # new key, add 

print("updated dictionary: ", dict_example)

# add the following if statements

if 'c' not in dict_example.keys():
    dict_example['c'] = 300

if 'e' not in dict_example.keys():
    dict_example['e'] = 5

print("conditionally updated dictionary: ", dict_example)

The output is:

Output
original dictionary: {'a': 1, 'b': 2} updated dictionary: {'a': 100, 'b': 2, 'c': 3, 'd': 4} conditionally updated dictionary: {'a': 100, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

The output shows that, because of the if condition, the value of c didn’t change when the dictionary was conditionally updated.

Add to Python Dictionary Using the update() Method

You can append a dictionary or an iterable of key-value pairs to a dictionary using the update() method. The update() method overwrites the values of existing keys with the new values.

The following example demonstrates how to create a new dictionary, use the update() method to add a new key-value pair and a new dictionary, and print each result:

site = {'Website':'DigitalOcean', 'Tutorial':'How To Add to a Python Dictionary'}
print("original dictionary: ", site)

# update the dictionary with the author key-value pair
site.update({'Author':'Sammy Shark'})
print("updated with Author: ", site)

# create a new dictionary
guests = {'Guest1':'Dino Sammy', 'Guest2':'Xray Sammy'}

# update the original dictionary with the new dictionary
site.update(guests)
print("updated with new dictionary: ", site)

The output is:

Output
original dictionary: {'Website': 'DigitalOcean', 'Tutorial': 'How To Add to a Python Dictionary'} updated with Author: {'Website': 'DigitalOcean', 'Tutorial': 'How To Add to a Python Dictionary', 'Author': 'Sammy Shark'} updated with new dictionary: {'Website': 'DigitalOcean', 'Tutorial': 'How To Add to a Python Dictionary', 'Author': 'Sammy Shark', 'Guest1': 'Dino Sammy', 'Guest2': 'Xray Sammy'}

The output shows that the first update adds a new key-value pair and the second update adds the key-value pairs from the guest dictionary to the site dictionary. Note that if your update to a dictionary includes an existing key, then the old value is overwritten by the update.

Add to Python Dictionary Using the Merge | Operator

You can use the dictionary merge | operator, represented by the pipe character, to merge two dictionaries and return a new dictionary object.

The following example demonstrates how to to create two dictionaries and use the merge operator to create a new dictionary that contains the key-value pairs from both:

site = {'Website':'DigitalOcean', 'Tutorial':'How To Add to a Python Dictionary', 'Author':'Sammy'}

guests = {'Guest1':'Dino Sammy', 'Guest2':'Xray Sammy'}

new_site = site | guests

print("site: ", site)
print("guests: ", guests)
print("new_site: ", new_site)

The output is:

Output
site: {'Website': 'DigitalOcean', 'Tutorial': 'How To Add to a Python Dictionary', 'Author': 'Sammy'} guests: {'Guest1': 'Dino Sammy', 'Guest2': 'Xray Sammy'} new_site: {'Website': 'DigitalOcean', 'Tutorial': 'How To Add to a Python Dictionary', 'Author': 'Sammy', 'Guest1': 'Dino Sammy', 'Guest2': 'Xray Sammy'}

The two dictionaries were merged into a new dictionary object that contains the key-value pairs from both dictionaries.

If a key exists in both dictionaries, then the value from the second dictionary, or right operand, is the value taken. In the following example code, both dictionaries have a key called b:

dict1 = {'a':'one', 'b':'two'}
dict2 = {'b':'letter two', 'c':'letter three'}

dict3 = dict1 | dict2

print{"dict3: ", dict3}

The output is:

Output
dict3: {'a': 'one', 'b': 'letter two', 'c': 'letter three'}

The value of key b was overwritten by the value from the right operand, dict2.

Add to Python Dictionary Using the Update |= Operator

You can use the dictionary update |= operator, represented by the pipe and equal sign characters, to update a dictionary in-place with the given dictionary or values.

Just like the merge | operator, if a key exists in both dictionaries, then the update |= operator takes the value from the right operand.

The following example demonstrates how to create two dictionaries, use the update operator to append the second dictionary to the first dictionary, and then print the updated dictionary:

site = {'Website':'DigitalOcean', 'Tutorial':'How To Add to a Python Dictionary', 'Author':'Sammy'}

guests = {'Guest1':'Dino Sammy', 'Guest2':'Xray Sammy'}

site |= guests

print("site: ", site)

The output is:

Output
site: {'Website': 'DigitalOcean', 'Tutorial': 'How To Add to a Python Dictionary', 'Author': 'Sammy', 'Guest1': 'Dino Sammy', 'Guest2': 'Xray Sammy'}

In the preceding example, you didn’t need to create a third dictionary object, because the update operator modifies the original object. The output shows that the guests dictionary was appended to the original site dictionary.

Performance Optimization and Best Practices

Choosing the Right Method for Performance

When working with large datasets or performance-critical applications, choosing the right dictionary update method can significantly impact your code’s efficiency:

Performance Comparison:

The following code compares the performance of three different methods for updating a large Python dictionary with another dictionary containing overlapping and new keys:

import time

# Create two large dictionaries with overlapping keys
large_dict1 = {f'key_{i}': f'value_{i}' for i in range(10000)}
large_dict2 = {f'key_{i+5000}': f'value_{i+5000}' for i in range(10000)}

# Method 1: Assignment operator inside a loop
# This approach updates (or adds) each key from large_dict2 to large_dict1 one at a time
start = time.time()
for key, value in large_dict2.items():
    large_dict1[key] = value
assignment_time = time.time() - start

# Method 2: Using the update() method
# This efficiently updates large_dict1 in-place with all items from large_dict2 at once
start = time.time()
large_dict1.update(large_dict2)
update_time = time.time() - start

# Method 3: Using the |= update operator (Python 3.9+)
# This is a shorthand for the update() method and also updates large_dict1 in-place
start = time.time()
large_dict1 |= large_dict2
update_operator_time = time.time() - start

print(f"Assignment: {assignment_time:.6f}s")
print(f"Update method: {update_time:.6f}s")
print(f"Update operator: {update_operator_time:.6f}s")
  • Assignment operator in a loop: Typically fastest for single items, but not optimal for bulk updates due to repeated operations.
  • update() method: Best for bulk updating; performs the update in a single call.
  • |= update operator: Available in Python 3.9 and later; behaves like update(), providing a clean and modern syntax.

Running this code will help you measure and compare the actual execution time of each method for large data sets.

Memory-Efficient Dictionary Operations

When working in environments where memory is limited, it’s important to write dictionary operations that minimize overhead and are as efficient as possible. Here’s an explanation of some memory-efficient techniques for handling dictionaries in Python, along with examples:

  • Using defaultdict for automatic key creation

Instead of manually checking if a key exists before updating it, you can use collections.defaultdict to automatically create keys with a default value. This can save both code and memory since it avoids extra lookups and error handling:

from collections import defaultdict

def count_words_efficiently(text):
    """
    Efficiently counts word occurrences in a string using defaultdict.
    defaultdict(int) initializes missing keys to 0 automatically.
    """
    word_count = defaultdict(int)
    for word in text.split():
        word_count[word] += 1
    # Optionally convert back to a standard dict
    return dict(word_count)
  • Using update() for merging multiple dictionaries

When you have several dictionaries to combine, it’s more memory-efficient to update a single dictionary in place, rather than building long temporary lists or using repeated lookups:

def merge_dictionaries_efficiently(*dicts):
    """
    Efficiently merges any number of dictionaries into a single one using update().
    This avoids the need to repeatedly copy dictionaries or perform many lookups.
    """
    result = {}
    for d in dicts:
        result.update(d)
    return result
  • Using the merge operator | for modern Python (3.9+)

Python 3.9 introduced the merge operator (|) which allows for merging dictionaries with a concise and modern syntax. While functionally similar to update(), this operator returns a new dictionary each time; for in-place updates, use |=. Here’s how to use it for efficiently merging dictionaries:

def merge_dictionaries_modern(*dicts):
    """
    Modern approach using the merge operator (Python 3.9+).
    Efficiently merges multiple dictionaries into one by applying |= in a loop.
    """
    result = {}
    for d in dicts:
        result |= d
    return result

All these techniques help keep your code efficient and concise, both in terms of CPU and memory usage, especially with large datasets or resource-constrained environments.

Advanced Dictionary Update Patterns

Working with dictionaries often goes beyond simple addition and updating — sometimes you need more powerful or safer ways to combine or modify data. Below are some advanced patterns for updating dictionaries in Python, complete with clear explanations.

1. Conditional Updates with Error Handling

Problem:
If you want to add new key-value pairs from one dictionary to another but avoid overwriting any existing keys, you need more control than the standard update() method offers.

Solution:
The function below adds key-value pairs from dict2 to dict1. By default, it only adds new keys that don’t exist in dict1. If you set overwrite=True, it will update any matching keys.

def safe_update(dict1, dict2, overwrite=False):
    """
    Update dict1 with dict2.
    If overwrite is False, only add keys that do not exist in dict1.
    If overwrite is True, update all keys (like dict.update()).
    """
    if overwrite:
        dict1.update(dict2)
    else:
        for key, value in dict2.items():
            if key not in dict1:
                dict1[key] = value
    return dict1

This pattern prevents accidental overwriting of important data by controlling how updates are applied.

2. Deep Merging for Nested Dictionaries

Problem:
Dictionaries often contain nested dictionaries (dictionaries as values). The standard update() or merge operator only works shallowly — inner dictionaries will be completely replaced.

Solution:
A deep merge recursively merges nested dictionaries, so only the overlapping keys are updated, while deeper structure is preserved when possible.

def deep_merge(dict1, dict2):
    """
    Recursively merge dict2 into dict1.
    If both dict1[key] and dict2[key] are dictionaries, merge them deeply.
    Otherwise, dict2's value overwrites dict1's.
    Returns a new merged dictionary.
    """
    result = dict1.copy()
    for key, value in dict2.items():
        if (
            key in result and
            isinstance(result[key], dict) and
            isinstance(value, dict)
        ):
            result[key] = deep_merge(result[key], value)
        else:
            result[key] = value
    return result

This deep merging technique is especially useful for combining configuration files or complex settings objects with nested structure.

Example: Deep Merge in Action

Suppose you have two configuration dictionaries for your app:

config1 = {
    'database': {'host': 'localhost', 'port': 5432},
    'cache': {'enabled': True}
}

config2 = {
    'database': {'port': 3306, 'ssl': True},  # change port, add ssl
    'api': {'timeout': 30}                    # add new section
}

merged_config = deep_merge(config1, config2)
print(merged_config)

Output:

Output
{ 'database': {'host': 'localhost', 'port': 3306, 'ssl': True}, 'cache': {'enabled': True}, 'api': {'timeout': 30} }
  • The 'database' settings are merged so that only 'port' and 'ssl' are updated or added, while existing keys like 'host' are preserved.
  • The new 'api' section is added.
  • The 'cache' section remains unchanged.

These patterns are particularly useful for configuration management, merging user settings, or any advanced dictionary work where you need more than the basics.

When to Use Each Method

Method Best For Performance Memory Usage
dict[key] = value Single item updates Fastest Low
update() Bulk operations Fast Low
| (merge) Creating new dictionaries Medium High (creates new)
|= (update) In-place bulk updates Fast Low

Frequently Asked Questions

1. How do I add things to a dictionary in Python?

To add an item to a dictionary, you use the syntax:

dictionary[key] = value

This will add a new key-value pair to the dictionary. If the key already exists, its value will be updated.

For example:

my_dict = {"a": 1}
my_dict["b"] = 2
print(my_dict)  # Output: {'a': 1, 'b': 2}

2. Can you append to a dictionary?

You cannot directly use methods like .append() for dictionaries as they are used for lists. However, you can add a key-value pair using dictionary[key] = value. To append values to an existing list stored in a dictionary, you need to modify the list.

my_dict = {"a": [1, 2]}
my_dict["a"].append(3)
print(my_dict)  # Output: {'a': [1, 2, 3]}

3. How do you add multiple items to a dictionary in Python?

You can use the .update() method to add multiple key-value pairs from another dictionary or an iterable of key-value pairs.

my_dict = {"a": 1}
my_dict.update({"b": 2, "c": 3})
print(my_dict)  # Output: {'a': 1, 'b': 2, 'c': 3}

Or using an iterable:

my_dict.update([("d", 4), ("e", 5)])
print(my_dict)  # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

4. What’s the difference between dict() and {} in Python?

Both create dictionaries, but {} is more efficient and commonly used:

# More efficient
my_dict = {}  # Empty dictionary
my_dict = {"a": 1, "b": 2}  # With key-value pairs

# Less efficient but functional
my_dict = dict()  # Empty dictionary
my_dict = dict(a=1, b=2)  # With key-value pairs

The {} syntax is faster because it’s a literal that Python can optimize at compile time.

5. How do you merge two dictionaries in Python?

There are several ways to merge dictionaries depending on your Python version:

Python 3.9+ (Recommended):

dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged = dict1 | dict2  # Creates new dictionary
# Or update in-place:
dict1 |= dict2

Older Python versions:

dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
dict1.update(dict2)  # Updates dict1 in-place

6. How do you add items to a dictionary without overwriting existing keys?

Use conditional checks before adding:

my_dict = {"a": 1, "b": 2}
new_items = {"b": 3, "c": 4}

for key, value in new_items.items():
    if key not in my_dict:
        my_dict[key] = value

print(my_dict)  # Output: {'a': 1, 'b': 2, 'c': 4}

7. What’s the most efficient way to update a dictionary?

For single items, use the assignment operator (=). For multiple items, use update():

# Single item (fastest)
my_dict["key"] = "value"

# Multiple items (most efficient for bulk operations)
my_dict.update({"key1": "value1", "key2": "value2"})

8. How do you handle dictionary updates in a loop efficiently?

Use update() for bulk operations instead of individual assignments:

# Less efficient
my_dict = {}
for i in range(1000):
    my_dict[f"key_{i}"] = f"value_{i}"

# More efficient
my_dict = {f"key_{i}": f"value_{i}" for i in range(1000)}
# Or if updating from another source:
my_dict.update({f"key_{i}": f"value_{i}" for i in range(1000)})

9. Can you add a dictionary to another dictionary?

Yes, you can merge dictionaries using several methods:

dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}

# Method 1: Update (modifies dict1)
dict1.update(dict2)

# Method 2: Merge operator (Python 3.9+)
merged = dict1 | dict2

# Method 3: Dictionary unpacking
merged = {**dict1, **dict2}

10. How do you add values to existing keys in a dictionary?

For numeric values, you can add directly. For lists, use append():

# Numeric values
my_dict = {"count": 5}
my_dict["count"] += 3
print(my_dict)  # Output: {'count': 8}

# List values
my_dict = {"items": [1, 2]}
my_dict["items"].append(3)
print(my_dict)  # Output: {'items': [1, 2, 3]}

11. What’s the difference between update() and the merge operator (|)?

  • update() modifies the original dictionary in-place
  • | creates a new dictionary without modifying the originals
dict1 = {"a": 1}
dict2 = {"b": 2}

# update() - modifies dict1
dict1.update(dict2)
print(dict1)  # Output: {'a': 1, 'b': 2}

# merge operator - creates new dictionary
dict1 = {"a": 1}
new_dict = dict1 | dict2
print(dict1)    # Output: {'a': 1} (unchanged)
print(new_dict) # Output: {'a': 1, 'b': 2}

12. How do you safely update a dictionary with error handling?

def safe_dict_update(target_dict, source_dict, overwrite=True):
    """Safely update dictionary with error handling."""
    try:
        if overwrite:
            target_dict.update(source_dict)
        else:
            for key, value in source_dict.items():
                if key not in target_dict:
                    target_dict[key] = value
        return True
    except (TypeError, AttributeError) as e:
        print(f"Error updating dictionary: {e}")
        return False

# Usage
my_dict = {"a": 1}
result = safe_dict_update(my_dict, {"b": 2, "c": 3})
print(my_dict)  # Output: {'a': 1, 'b': 2, 'c': 3}

To learn more about dictionaries in Python, refer to this tutorial on Understanding Dictionaries in Python.

Conclusion

In this comprehensive guide, you learned four essential methods for adding and updating Python dictionaries: the assignment operator, update() method, merge operator (|), and update operator (|=). Each method has its specific use cases and performance characteristics.

  • Assignment operator (=): Best for single item updates and offers the fastest performance
  • update() method: Most efficient for bulk operations and merging multiple dictionaries
  • Merge operator (|): Creates new dictionaries without modifying originals (Python 3.9+)
  • Update operator (|=): In-place updates for bulk operations (Python 3.9+)

Performance considerations:

  • Use {} instead of dict() for better performance
  • Choose the right method based on your specific use case
  • Consider memory usage when working with large datasets

Next steps:

Continue your learning with more Python tutorials and explore advanced topics like Python Counter and Using the Collections Module in Python.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Anish Singh Walia
Anish Singh Walia
Author
Sr Technical Writer
See author profile

I help Businesses scale with AI x SEO x (authentic) Content that revives traffic and keeps leads flowing | 3,000,000+ Average monthly readers on Medium | Sr Technical Writer @ DigitalOcean | Ex-Cloud Consultant @ AMEX | Ex-Site Reliability Engineer(DevOps)@Nutanix

Pankaj Kumar
Pankaj Kumar
Author
See author profile

Java and Python Developer for 20+ years, Open Source Enthusiast, Founder of https://www.askpython.com/, https://www.linuxfordevices.com/, and JournalDev.com (acquired by DigitalOcean). Passionate about writing technical articles and sharing knowledge with others. Love Java, Python, Unix and related technologies. Follow my X @PankajWebDev

Category:
Tags:

Still looking for an answer?

Was this helpful?

thanks it really helped! have a question tho, can you make mathematical operations in the values to the keys?

- confused

What will happen if you don’t add the .keys()? will it also check if the values of keys are the value you want to input?

- Niik

You don`t need keys() d={c: alpha} if c in d: pass

- RTFM

Thank you, this information was clearly laid out!

- KMJ248

how can add new column in tuple # List of tuples listofTuples = [(“Riti” , 11), (“Aadi” , 12), (“Sam” , 13),(“John” , 22),(“Lucy” , 90)] thank

- hamza

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.