Editor

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 lesson

Use 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

All Python exercises · 50 practice problems · Data Structures quiz