Dictionary and Set Comprehensions
Explore how to create unique sets and transformed dictionaries using Python's dictionary and set comprehensions. Understand merging lists into dictionaries, dictionary inversion, and how these tools help write clear, efficient code.
We'll cover the following...
We have already seen how list comprehensions transform loops into concise, readable one-liners for creating lists. However, Python’s comprehension syntax is not limited to ordered sequences. When we need to ensure data uniqueness or establish mapping relationships, we can apply the same logic to sets and dictionaries.
In this lesson, we will extend our comprehension skills to build lookup tables and unique collections expressively, reducing the boilerplate often associated with creating these data structures.
Set comprehensions
A set comprehension allows us to build a set (a collection of unique elements) by iterating over an iterable. The syntax is nearly identical to a list comprehension, but instead of square brackets [], we use curly braces {}.
{expression for item in iterable}
If the expression generates a value that is already in the set, Python automatically discards the duplicate, as sets do not allow duplicates.
In the following example, we have a list of user inputs with inconsistent capitalization. We want a unique set of normalized, ...