I can’t wrap my head around the code below. Can someone please enlighten me?
How is it possible that when the code newdict[word] = len(word) runs, it knows that it’s the VALUE and not the KEY that it needs to update?
newdict[word] = word
newdict[word] = len(word)
def word_length_dictionary(words):
newdict = {}
for word in words:
newdict[word] = word
newdict[word] = len(word)
return newdict
Also, I’m still trying to get a good grip on Dictionaries and although I might be able to finish this topic, I may not be confident enough to move forward. Do you suggest I re-take the whole practice? Should I read up/watch from other resources online to solidify my knowledge? I welcome any suggestions. Thank you for your help.
Double check the location of your return statement (indentation is important).
It may also be worth reconsidering the location of dict[word] = len(list) as it’s currently indented to the same level as where you create the list so it changes on every iteration which is unnecessary. You could also consider using len directly on a string since that is supported.
def inverse_word_length(words):
word_lengths = {}
for word in words.split():
key = f"{len(word)}"
if key not in word_lengths.keys():
word_lengths[key] = [word]
else:
word_lengths[key] += [word]
return dict(sorted(word_lengths.items()))
print (inverse_word_length("A quick brown fox jumps over the lazy dog"))