Set and Dictionary Comprehensions

Learn about the set and dictionary comprehensions and their implementation using a coding example.

We'll cover the following

Overview

Comprehensions aren’t restricted to lists. We can use a similar syntax with braces to create sets and dictionaries as well. Let’s start with sets. One way to create a set is to wrap a list comprehension in the set() constructor, which converts it to a set. But why waste memory on an intermediate list that gets discarded, when we can create a set directly?

Example

Here’s an example that uses a named tuple to model author, title, and genre triples and then retrieves a set of all the authors that write in a specific genre:

Get hands-on with 1200+ tech skills courses.