Benchmark Key Value Swapping of a Dictionary in Python
Today, I was writing a python script and needed to swap the keys and values in a dictionary. While doing it, I wanted to see how long it takes to perform such a swap operation on small dictionaries.
To determine which solution is the fastest on CPU, we can use the timeit
module in Python to benchmark each solution.
The methods I will be testing is that
- A similar way to list comprehension
- using
zip()
- Iterating the dictionary keys with for loop
Here’s an example benchmark:
import timeit
existing_dict = {"a": 1, "b": 2, "c": 3}
def solution1():
return {v: k for k, v in existing_dict.items()}
def solution2():
return dict(zip(existing_dict.values(), existing_dict.keys()))
def solution3():
swapped_dict = {}
for k, v in existing_dict.items():
swapped_dict[v] = k
return swapped_dict
print("Solution 1:", timeit.timeit(solution1, number=100000))
print("Solution 2:", timeit.timeit(solution2, number=100000))
print("Solution 3:", timeit.timeit(solution3, number=100000))
This code benchmarks each solution by running it 100,000 times and measuring the time it takes to complete.
Results
On my machine, the results are:
Solution 1: 0.245 seconds
Solution 2: 0.342 seconds
Solution 3: 0.445 seconds
Don’t forget that these results may vary depending on the size of the input dictionary and the specific hardware and software configuration of your machine.