Register to get access to free programming courses with interactive exercises

Sets and dictionary generators Python: Declarative programming

Imagine a Python programmer. With a list of pairs of values to hand, they can always get a set of unique pairs by applying set(). It's easy to get a dictionary from this set by applying the dict() function. It seems that with list generators, we can describe dictionaries and sets as declarative, like lists.

However, this isn't an optimal solution in most cases: the entire intermediate list will be created and stored in memory. It'll be annoying to waste extra memory if there are many repeated values or keys when generating elements of a set or dictionary.

Python comes to our rescue — set generators and dictionary generators, which we'll look at in this lesson.

Set generators

With these generators, everything is super simple. It only takes two actions:

  • Take the expression that defines the list generator
  • Replace the square brackets with curly brackets

Let's see how it works:

squares = {x * x for x in range(10)}
# {0, 1, 64, 4, 36, 9, 16, 49, 81, 25}
5 * 5 in squares
# True

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

<span class="translation_missing" title="translation missing:">Bookmate</span>
<span class="translation_missing" title="translation missing:">Healthsamurai</span>
<span class="translation_missing" title="translation missing:">Dualboot</span>
<span class="translation_missing" title="translation missing:">Abbyy</span>
Suggested learning programs
Developing web applications with Django
10 months
from scratch
under development
Start at any time

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.