Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
Group these words by their length, in a dictionary where the key is the length and the value is the list of words: ["cat", "tree", "dog", "bird", "sun", "house"]. Show the groups from the shortest length to the longest.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Plan. The key is len(word). The value is a list. If the key is new, make an empty list. Then append.
Check. The lengths are 3 for cat, dog and sun; 4 for tree and bird; 5 for house. The output is
3 ['cat', 'dog', 'sun']
4 ['tree', 'bird']
5 ['house']The keys are numbers here, which is fine: a number is a fixed value and can be a key.
Answer: The program above.
Log in to join the discussion.
Loading…