By Anish Singh Walia and Pankaj Kumar
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.
=
), update()
method, merge operator (|
), and update operator (|=
) for different use cases{}
instead of dict()
for initialization, and choose the right method based on your specific needs|
) creates new dictionaries, while update()
and |=
modify existing ones in-placeDeploy your Python applications from GitHub using DigitalOcean App Platform. Let DigitalOcean focus on scaling your app.
=
Assignment OperatorYou 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:
Outputoriginal 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
.
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:
Outputoriginal 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.
update()
MethodYou 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:
Outputoriginal 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.
|
OperatorYou 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:
Outputsite: {'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:
Outputdict3: {'a': 'one', 'b': 'letter two', 'c': 'letter three'}
The value of key b
was overwritten by the value from the right operand, dict2
.
|=
OperatorYou 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:
Outputsite: {'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.
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")
Running this code will help you measure and compare the actual execution time of each method for large data sets.
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:
defaultdict
for automatic key creationInstead 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)
update()
for merging multiple dictionariesWhen 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
|
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.
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.
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.
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.
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}
}
'database'
settings are merged so that only 'port'
and 'ssl'
are updated or added, while existing keys like 'host'
are preserved.'api'
section is added.'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.
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 |
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}
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]}
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}
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.
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
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}
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"})
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)})
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}
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]}
update()
and the merge operator (|
)?update()
modifies the original dictionary in-place|
creates a new dictionary without modifying the originalsdict1 = {"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}
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.
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.
=
): Best for single item updates and offers the fastest performanceupdate()
method: Most efficient for bulk operations and merging multiple dictionaries|
): Creates new dictionaries without modifying originals (Python 3.9+)|=
): In-place updates for bulk operations (Python 3.9+)Performance considerations:
{}
instead of dict()
for better performanceNext steps:
collections
module for advanced dictionary operationsContinue 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.
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
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
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
how can add new column in tuple # List of tuples listofTuples = [(“Riti” , 11), (“Aadi” , 12), (“Sam” , 13),(“John” , 22),(“Lucy” , 90)] thank
- hamza
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.