Could this be solved with list comprehension?

For anyone wondering where to use a list comprehension, this is the place to do it. Here is the code I used to solve this question.

def word_length_dictionary(words):
  return {word:len(word) for word in words}
6 Likes

Your solution is so much simpler than mine! Here’s what I did to implement list comprehension:

def word_length_dictionary(words):
  return {key:value for key, value in zip(words, list(map(lambda x: len(x), words)))}

instead of iterating through a list which had to iterate through the map, iterate through map

that’s just len

If you have key-value pairs you can convert that to dict without the comprehension

comprehension is itself map (do something on each value) (and also filter, (if))

  return dict(zip(words, map(len, words)))
  return {word: len(word) for word in words}

nice one! thanks for the example!

def word_length_dictionary(words):
  return {w:len(w) for w in words}
1 Like

Slight point in terminology. This is dictionary comprehension as the output is a dictionary, list comprehension would be making a list.

Hi there,

I have a similar solution:

def word_length_dictionary(words):
    for word in words:
      return {word: len(word)}

but this doesn´t iterate throught the word-list.
It just returns {“apple”: 5}
Can anyone tell, where I went wrong?

What happens when return is encountered in a loop, or anywhere else for that matter?

:woman_facepalming:
Thanks for the hint.

1 Like

I was inspired by this solution. but I solved the problem of that example:

def word_length_dictionary(words):
  new_dic = {}
  for word in words:
    new_dic[word] = len(word)
  return new_dic