Hackbright Code Challenges

Word Lengths: Solution

Word Lengths: Solution

Problem

Word Lengths

Whiteboard

Easier

Concepts

Dictionaries, Loops

Download

word-lengths-solution.zip


wordlengths.py
def word_lengths(sentence):
    """Get dictionary of word-length: {words}."""

    # START SOLUTION

    lengths = {}

    words = sentence.split()

    for word in words:
        if len(word) not in lengths:
            lengths[len(word)] = set()

        lengths[len(word)].add(word)

    return lengths

setdefault

In our solution, we say:

if len(word) not in lengths:
    lengths[len(word)] = set()

lengths[len(word)].add(word)

There’s an advanced idiom in Python using the dict.setdefault() method. setdefault takes two arguments, the key and the object to add to the dictionary if that key isn’t present. Regardless of whether it just added the set or whether it was already there, setdefault returns it to us. Since a set is a mutable object, we can just mutate the copy we were returned:

lengths.setdefault(len(word), set()).add(word)

To be honest, setdefault is tricky and not intuitive to read, so it’s often best avoided for clarity.

As a side note, setdefault is unrelated to the set type — we just happen to be adding a set to our dictionary in that line using setdefault.