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.
Loading...
Related Quiz
- What is the difference between import module and from module import * in terms of namespace pollution?
- A ____ is a linear data structure where the elements are arranged in a circular fashion.
- Which Python function is used to open a file for reading?
- If you have a function named fun inside a module named mod, how can you import it directly?
- For loops in Python utilize the ______ method internally to iterate over items.