Here's the solution:
def group_by_length(words):
groups = {}
for word in words:
length = len(word)
if length not in groups:
groups[length] = []
groups[length].append(word)
return groups
Or with setdefault():
def group_by_length(words):
groups = {}
for word in words:
groups.setdefault(len(word), []).append(word)
return groups