Search⌘ K
AI Features

Set and Dictionary Comprehensions

Explore set and dictionary comprehensions to efficiently create collections directly from iterables. Understand how to build sets that automatically remove duplicates and dictionaries that map keys to values, improving data lookup and manipulation within Python's iterator framework.

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, ...