Back to course

Dictionary and Set Comprehensions

Python Programming: The 0 to Hero Bootcamp

Dictionary and Set Comprehensions

Just like lists, dictionaries and sets can be created using compact, single-line comprehension syntax.

Set Comprehension

Syntax: {expression for item in iterable}

python

Goal: Get unique lengths of words

words = ['hello', 'world', 'python', 'hello']

lengths_set = {len(w) for w in words} print(lengths_set) # Output: {5, 6}

Example 2: Squaring unique numbers from a list

numbers = [1, 2, 2, 3, 4, 3, 1] unique_squares = {n ** 2 for n in numbers} print(unique_squares) # Output: {1, 4, 9, 16}

Dictionary Comprehension

Syntax: {key_expression: value_expression for item in iterable}

python

Goal: Create a dictionary mapping letters to their uppercase versions

letters = ['a', 'b', 'c']

mapping = {k: k.upper() for k in letters} print(mapping) # {'a': 'A', 'b': 'B', 'c': 'C'}

Example 2: Conditional filtering in dictionaries

stock_prices = {'AAPL': 150, 'GOOG': 2800, 'TSLA': 600, 'AMZN': 3000}

Only include stocks priced under 1000

low_stocks = {ticker: price for ticker, price in stock_prices.items() if price < 1000} print(low_stocks) # {'AAPL': 150, 'TSLA': 600}