You are given a list of words and you need to create a dictionary where keys are words and values are their respective lengths. Which Python construct will be most efficient for this?

  • word_lengths = {word: len(word) for word in words}
  • word_lengths = {} for i in range(len(words)): word_lengths[words[i]] = len(words[i])
  • word_lengths = {} for word in words: word_lengths[word] = len(word)
  • word_lengths = {} len(words, key=lambda x: word_lengths[word])
The most efficient way to create a dictionary with words as keys and their respective lengths as values is to use a dictionary comprehension. It is concise and Pythonic, iterating over the list of words and calculating the length of each word in a single step.
Add your answer
Loading...

Leave a comment

Your email address will not be published. Required fields are marked *