Introduction
Dictionary comprehension helps create dictionaries quickly and clearly in one line. It saves time and makes code easier to read.
Jump into concepts and practice - no test required
Dictionary comprehension helps create dictionaries quickly and clearly in one line. It saves time and makes code easier to read.
{key_expression: value_expression for item in iterable if condition}key_expression and value_expression define what each key and value will be.if condition part is optional and lets you include only some items.{x: x*x for x in range(5)}{x: x*x for x in range(10) if x % 2 == 0}{word: len(word) for word in ['apple', 'banana', 'cherry']}This program makes a dictionary where each fruit name is a key and its length is the value.
fruits = ['apple', 'banana', 'cherry'] lengths = {fruit: len(fruit) for fruit in fruits} print(lengths)
Dictionary comprehension is faster and cleaner than using loops to build dictionaries.
Use it when the logic is simple; for complex cases, normal loops might be clearer.
Dictionary comprehension creates dictionaries quickly in one line.
It can include conditions to filter items.
It makes code shorter and easier to read.
dictionary comprehension in Python?nums = [1, 2, 3]
squares = {n: n**2 for n in nums if n > 1}
print(squares)data = [1, 2, 3]
result = {x, x*2 for x in data}words = ['apple', 'banana', '', 'cherry', None]. How can you use dictionary comprehension to create a dictionary with words as keys and their lengths as values, but only include non-empty and non-None words?if w filters out empty strings and None automatically.