Skip to main content

Pythonic Data Structures

Dict and Set Comprehensions

0:00
LearnStep 1/3

Mastering Dict and Set Comprehensions

Just as list comprehensions provide a concise way to create lists, Python offers similar syntax for dictionaries and sets. These comprehensions are not only more readable but often faster than standard for-loops.

Dictionary Comprehensions

The syntax for a dictionary comprehension is {key_expr: value_expr for item in iterable if condition}.

python

Inverting a Dictionary

You can easily swap keys and values using a comprehension.

python

Set Comprehensions

Set comprehensions use curly braces {} like dictionaries but without key-value pairs. They automatically remove duplicates.

python