DEV Community

Cover image for #Day27 - Fastest Way to Combine Dictionaries
Rahul Banerjee
Rahul Banerjee

Posted on • Originally published at realpythonproject.com

#Day27 - Fastest Way to Combine Dictionaries

We know the fastest way to combine lists. Today we will try to find the fastest way to combine dictionaries

We will be considering the following ways

  • Using a for loop
  • Using the update() method
  • Using the ChainMap Function
  • Using the unpacking operator
  • Using the pipe operator ( | )
  • Using the (|=) operator

How are we going to measure the performance?

image.png

We have a couple of dictionaries with 1000 key-value pairs in each dictionary. We will update function func to perform the different combination methods. The function will be called 100 times and we will print the average run time.

Using a for loop

image.png

We simply iterate over the second dictionary and add its elements to the first dictionary.
Below is the output

On average, it took 6.765522999558016e-05 seconds
Enter fullscreen mode Exit fullscreen mode

Using the update method

image.png

Similar to the for loop approach, the first dictionary is updated. The elements of the second dictionary are added to the first dictionary. If there is a common key present, the value for the key in the first dictionary will be overwritten by that of the second dictionary.

On average, it took 2.554959000008239e-05 seconds
Enter fullscreen mode Exit fullscreen mode

Using the ChainMap Function

image.png
Unlike the previous two approaches, a new dictionary is created and the original dictionaries are not updated. Below is the output

On average, it took 9.942399992723949e-07 seconds
Enter fullscreen mode Exit fullscreen mode

Using the unpacking operator

image.png

In this approach as well, we create a new dictionary. The original dictionaries are not updated.
Below is the output

On average, it took 7.01560299967241e-05 seconds
Enter fullscreen mode Exit fullscreen mode

Using the | operator

image.png

In Python 3.9, the pipe operator was introduced to combine dictionaries. Below is the output

On average, it took 5.5255000000000026e-05 seconds
Enter fullscreen mode Exit fullscreen mode

Using the |= operator

image.png

Along with the | operator, the |= operator was introduced in Python 3.9. Below is the output

On average, it took 3.0259589999999983e-05 seconds
Enter fullscreen mode Exit fullscreen mode

Comparison

download.png

The ChainMap() method seems to be the fastest

Top comments (0)