Word Length Dictionary Practice Problem
This data science coding problem helps you practice List & Dict Comprehensions, word length dictionary, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of List & Dict Comprehensions.
- Problem ID: 95
- Problem key: 95-word-length-dictionary
- URL: https://datacrack.app/solve/95-word-length-dictionary
- Difficulty: easy
- Topic: List & Dict Comprehensions
- Module: Python Fundamentals
Problem Statement
# 🧩 Word Length Dictionary
---
### 🎯 Goal
**Dictionary comprehensions** let you build dictionaries in a single readable expression. This problem teaches `{key: value for item in iterable}` — the dict comprehension syntax, which is foundational for feature engineering and data transformation in data science.
---
### 🔍 Dict Comprehension Syntax
```python
{expression_key: expression_value for item in iterable}
```
For example:
```python
{word: len(word) for word in sentence.split()}
```
---
### 💻 Task
Implement `word_lengths(sentence)` using a **dict comprehension**.
---
### 📥 Input
- `sentence`: a string of space-separated words (all lowercase, no punctuation)
### 📤 Output
- A dict mapping each word to its character length
---
### 🧩 Starter Code
```python
def word_lengths(sentence):
"""
Build a dictionary mapping each word to its length.
Args:
sentence (str): Space-separated words
Returns:
dict: {word: len(word)} for each word
"""
# 🧠 TODO: Split the sentence into words
# 🧠 TODO: Use a dict comprehension to map each word to its length
pass
```
---
### 💡 Example
```python
word_lengths("the quick brown fox")
# Expected: {"the": 3, "quick": 5, "brown": 5, "fox": 3}
```
---
### 🔑 Key Concepts
- `str.split()` — splits on whitespace, returns a list of words
- `len(word)` — character count
- Dict comprehension: `{word: len(word) for word in words}`
- In NLP, this is the first step toward building a vocabulary or bag-of-words featureStarter Code
def word_lengths(sentence):
"""
Build a dictionary mapping each word to its length.
Args:
sentence (str): Space-separated words
Returns:
dict: {word: len(word)} for each word
"""
# 🧠 TODO: Split the sentence into words
# 🧠 TODO: Use a dict comprehension to map each word to its length
pass