How To Add Two Dictionaries In Python With Same Keys

In this tutorial, we will learn how to add two dictionaries in Python with the same keys. This is a common task when combining data from various sources or aggregating values from two datasets.

Python provides several ways to merge dictionaries, and we will discuss some of the easiest and most commonly used methods.

Step 1: Using a For Loop

A for loop is an easy way to iterate through the keys in two dictionaries and perform the addition. Here’s a step-by-step guide to adding the values of two dictionaries with the same keys using a for loop:

  1. Create two dictionaries with the same keys.
  2. Initialize an empty dictionary to store the sum of the values for each key.
  3. Iterate through the keys of one of the dictionaries.
  4. For each key, add the values from both dictionaries and store the result in the new dictionary.

Here’s an example:

This will output:

{'a': 5, 'b': 7, 'c': 9}

Step 2: Using Dictionary Comprehension

We can achieve the same result more concisely using dictionary comprehension. A dictionary comprehension is a concise way to create a dictionary in a single line of code.

Here’s how to add two dictionaries using dictionary comprehension:

This line of code does the same thing as the for loop in the previous step, but it’s shorter and more readable.

Here’s the full code using dictionary comprehension:

This will output the same result as before:

{'a': 5, 'b': 7, 'c': 9}

Step 3: Using the update() Method

If you want to update the first dictionary with the sum of both dictionaries, you can use the update() method. The update() method takes a dictionary as an argument and updates the current dictionary with the provided dictionary.

Here’s how to add two dictionaries and update the first dictionary using the update() method:

Here’s the full code using the update() method:

This will output:

{'a': 5, 'b': 7, 'c': 9}

Full Code Examples

Here are the full code examples for each method:

Using a for loop:

Using dictionary comprehension:

Using the update() method:

Conclusion

In this tutorial, we have learned three different methods to add two dictionaries in Python with the same keys. We covered the use of a for loop, dictionary comprehension, and the update() method. Depending on your requirements and coding style, you can choose the method that is most suitable for your specific use case.