Write a function that groups words by their length.
group_by_length(words)
Return a dict mapping each word length to a list of the words of that length, in the order they appeared in words.
group_by_length(["cat", "dog", "a", "bird", "ox", "at"])
// → {3: ["cat", "dog"], 1: ["a"], 4: ["bird"], 2: ["ox", "at"]}
group_by_length(["a", "b", "c"])
// → {1: ["a", "b", "c"]}
The tricky part isn't grouping by length — it's handling the first word of a given length, when there's no list to append to yet.
def group_by_length(words):
groups = {}
for word in words:
groups.setdefault(len(word), []).append(word)
return groups
.setdefault(key, default) is like .get()'s sibling, with one extra behavior: if key isn't in the dict yet, it stores default under that key (not just returns it) — and either way, it returns whatever ends up stored there. So groups.setdefault(len(word), []) does one of two things depending on whether that length has been seen before:
setdefault creates a new empty list, stores it under groups[len(word)], and returns that same (now-stored) empty list.setdefault just returns the existing list, untouched.Either way, you get back a real list that's already the one stored in groups, and .append(word) immediately adds to it. Without .setdefault(), you'd need an explicit check:
for word in words:
length = len(word)
if length not in groups:
groups[length] = []
groups[length].append(word)
Both versions do the same thing — .setdefault() just collapses the "does this key exist yet?" check and the list creation into one line.
def group_by_length(words):
groups = {}
for word in words:
groups.setdefault(len(word), []).append(word)
return groups
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.