Skip to main content

Posts

Showing posts with the label Python Programming Tips

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:" , time...