Challenges : Word Length Dict

Can someone point out what mistake i have made in this exercise?

Here is my code

def word_length_dictionary(words): for wor in words: keys = [] keys.append(wor) values = [] values.append(len(wor)) dictionary = dict(zip(keys, values)) return dictionary print(word_length_dictionary(["apple", "dog", "cat"]))

Then, the output is {‘cat’: 3}.
the answer should be {“apple”:5, “dog”: 3, “cat”:3}

I think the problem is that’s you’re redoing the dictionary variable inside the loop,
so you replace it on each iteration.

I think that you’d need to create that dictionary before the loop, as an empty dictionary:
dictionary = dict();
and then just add to it inside the loop:
dictionary.update(dict(zip(keys, values)))

if you fix the place of your variable declaration your code will give you the intended result. i.e if you declare your variable inside the loop you can only access the variable inside the loop. if you declare the variable inside the function you can only access the variable inside the function. Variable lives where they declarer.

def word_lenght(words): dictionary = {} keys = [] values =[] for word in words: keys.append(word) values.append(len(values)) dictionary = dict(zip(keys, values)) return dictionary print(word_lenght(["Lion", "dog", "cat"]))

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.