Blog Post #69: Combining Dictionaries: The Power of the update() Method

As we build more complex applications, we often find ourselves with data spread across multiple dictionaries. You might have a dictionary of default settings and another with a user’s custom settings, or a user’s basic profile and their contact information stored separately. The question then becomes: how do you efficiently merge them?

In this post, we will learn about the dictionary’s built-in .update() method, a powerful and common technique for combining the contents of one dictionary into another.

How .update() Works

The .update() method is called on a dictionary and takes another dictionary as its argument. It iterates through the key-value pairs of the second dictionary and merges them into the first one, following two simple rules:

  1. If a key from the second dictionary does not exist in the first one, the key-value pair is added.
  2. If a key from the second dictionary already exists in the first one, the value in the first dictionary is updated (overwritten) with the new value.

This operation modifies the original dictionary in-place.

.update() in Action

Let’s look at two common use cases.

Example 1: Adding New Information

Here, we have a basic user profile and we want to merge in their contact information from another dictionary.

user_profile = {"name": "Alice", "age": 30}
contact_info = {"email": "alice@example.com", "city": "New York"}

print(f"Before update: {user_profile}")

# Update the user_profile with the contact_info
user_profile.update(contact_info)

print(f"After update: {user_profile}")

The output shows that the new key-value pairs from contact_info have been added to user_profile:

Before update: {'name': 'Alice', 'age': 30}
After update: {'name': 'Alice', 'age': 30, 'email': 'alice@example.com', 'city': 'New York'}

Example 2: Overwriting Default Values

This is a very powerful pattern. Imagine you have a set of default settings for an application, and you want to apply a user’s custom settings over them.

default_settings = {"theme": "light", "font_size": 12, "show_sidebar": True}
user_settings = {"font_size": 14, "show_sidebar": False}

print(f"Defaults: {default_settings}")

# Apply the user's custom settings over the defaults
default_settings.update(user_settings)

print(f"Final settings: {default_settings}")

The output shows that the existing keys were updated, while the unique key from the original dictionary was preserved:

Defaults: {'theme': 'light', 'font_size': 12, 'show_sidebar': True}
Final settings: {'theme': 'light', 'font_size': 14, 'show_sidebar': False}

A Modern Alternative: The Merge Operator (|)

For those using Python 3.9 or newer, there is a more concise and readable syntax for merging dictionaries: the merge operator |.

Crucially, unlike .update() which modifies a dictionary in-place, the | operator creates and returns a new dictionary, leaving the original dictionaries unchanged.

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

# The value for key 'b' from dict2 will overwrite the one from dict1
merged_dict = dict1 | dict2

print(f"New merged dict: {merged_dict}")
print(f"Original dict1 is unchanged: {dict1}")
print(f"Original dict2 is unchanged: {dict2}")

The output is:

New merged dict: {'a': 1, 'b': 3, 'c': 4}
Original dict1 is unchanged: {'a': 1, 'b': 2}
Original dict2 is unchanged: {'b': 3, 'c': 4}

What’s Next?

You now have two powerful ways to combine dictionaries. The .update() method is perfect for modifying a dictionary in-place with new data, while the modern merge operator | is a clean way to create a new, combined dictionary. These are essential tools for managing complex data.

So far, our dictionary values have been simple data types like strings and numbers. But the real power of dictionaries comes when their values are other collections, like lists or even other dictionaries. In Post #70, we will explore how to build complex, hierarchical data structures by nesting dictionaries and lists.

Author

Debjeet Bhowmik

Experienced Cloud & DevOps Engineer with hands-on experience in AWS, GCP, Terraform, Ansible, ELK, Docker, Git, GitLab, Python, PowerShell, Shell, and theoretical knowledge on Azure, Kubernetes & Jenkins. In my free time, I write blogs on ckdbtech.com

Leave a Comment