Dict Comprehension in Python

Level 389 keystrokes

This creates a dictionary mapping words to their lengths using dict comprehension. It's a concise way to build dictionaries.

Python code

# Create a list of words
1words = ["apple", "banana", "cherry"]
# Dict comprehension: {key: value for item in iterable}
# Creates a dict with word as key and its length as value
2lengths = {w: len(w) for w in words}
# Print the resulting dictionary
3print(lengths)

Output

{'apple': 5, 'banana': 6, 'cherry': 6}
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • "× 6
  • ,× 2
  • (× 2
  • )× 2
  • =× 2
  • :× 1
  • [× 1
  • ]× 1
  • {× 1
  • }× 1

More Python examples at level 3

← Python typing practice