Hi Pythonistas, Today we are going to analyze the performance of different ways of accessing the dictionary in Python.
Let's consider the example
Using loop the dict and access using key
def looping_using_key():
data = {str(i): i for i in range(20)}
for key in data:
a = data[key]
Using items method
def looping_using_items():
data = {str(i): i for i in range(20)}
for key, value in data.items():
a = value
Analysis using the timeit module
time_taken = timeit.timeit(looping_using_key, number=10000)
print("Time taken using key: ", time_taken)
time_taken = timeit.timeit(looping_using_items, number=10000)
print("Time taken using item: ", time_taken)
Output
Time taken using key: 0.04307970999798272
Time taken using item: 0.039506489996711025
Why
In the first method, we are accessing the dictionary using a key so for every check, we need to find the hash of the key and fetch the item.
In the second method, the items method returns the list of tuple of key-value pair. So there is additional lookup. So it faster
Bonus
If we need only the values we have the values method this is faster than the items method.
Using values method
def looping_using_values():
data = {str(i): i for i in range(20)}
for value in data.values():
a = value
time_taken = timeit.timeit(looping_using_values, number=10000)
print("Time taken using value: ", time_taken)
Time taken using value: 0.033650106997811235
Tip
Use items, values methods for looping the data in the dictionary.
Hope you have learned something from this post. Please share your suggestion with afsal@parseltongue.co.in