Member-only story
Python Speed Optimization: Retrieve Values from a Dictionary Over 50% Faster!
Discover a trick that can significantly speed up value retrieval from Python dictionaries.
In daily work, most of the time it is required to extract multiple values from a Python dictionary in correspondence to multiple keys. This can be achieved by writing a for loop like this:
items = list()
for key in keys:
items.append(dict_[keys])
Or can be written as a one-line loop like this:
[dict_[key] for key in keys]
However, this can, sometimes, lead to growing runtime complexity as the loops grows with the number of keys to be extracted.
A better solution would be to use python ‘operator’.
list(operator.itemgetter(*keys)(dict_to_get_from))
This is not only cleaner, but also ~50% faster after experimenting it!
In the following experience, I tried both methods on a mock dictionary and, on average, the ‘itemgetter’ is ~1.9 times faster than list comprehension.