Create a Dict Comprehension
Intermediate · Write the code · from Python Comprehensions: List, Dict, Set, and Generator in One Guide
From the lesson: Python Comprehensions: List, Dict, Set, and Generator in One Guide
Imagine you have a list of 100 numbers and you want a new list containing only the even ones, each doubled. With a regular loop, that takes four lines. With a Python comprehension, it takes one.
Read the lessonUse a dict comprehension to create a dictionary called name_lengths that maps each name to its length.
Expected output:
{'Alice': 5, 'Bob': 3, 'Charlie': 7}names = ['Alice', 'Bob', 'Charlie']
# Create name_lengths using a dict comprehension
print(name_lengths)
More Comprehensions exercises
- Double Every NumberBeginner
- Filter Even NumbersBeginner
- Predict the Output: if vs if-elseIntermediate
- Unique Vowels with a Set ComprehensionIntermediate
- Fix the Bug: Wrong Comprehension SyntaxIntermediate
- Refactor a Loop into a ComprehensionIntermediate
- Flatten a MatrixAdvanced
All Python exercises · 50 practice problems · Data Structures quiz