Mapping functions should work faster than dict comprehensions:
translations = dict(zip(word_list, map(translate, word_list)))
What happens here is:
- We apply the function to each element in
word_list
, returning a map
object
- Combine it into a sequence (
zip
object) of one-to-one element tuples from the original list and that map object
- Convert the resulting sequence into a dictionary
After setting up a test program, it appears that there is a slight performance improvement. This is the code:
from datetime import datetime
def translate(wo):
return wo.upper()
word_list = {str(i):str(i+1) for i in range(50000)}
d = datetime.now()
translations = dict(zip(word_list, map(translate, word_list)))
print(datetime.now() - d)
d = datetime.now()
translations = {word: translate(word) for word in word_list}
print(datetime.now() - d)
After a few runs, the second printed time is always greater than the first one, which proves the efficiency.