Python ยท comprehensions

Dict & Set Comprehensions

Build a whole dictionary or set in one line: take items from an iterable, optionally filter them, and transform each one.

Dict comprehension


        # basic dict comprehension
        squares = {x: x**2 for x in range(5)}
        # ans: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
      

Dict from two lists


        # zip two lists
        keys = ["a", "b", "c"]
        values = [1, 2, 3]
        d = {k: v for k, v in zip(keys, values)}
        # ans: {'a': 1, 'b': 2, 'c': 3}
      

Dict with a condition


        # filter dict
        numbers = range(10)
        even_squares = {x: x**2 for x in numbers
                                if x % 2 == 0}
        # ans: {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
      

Swap keys and values


        # swap dict
        original = {"a": 1, "b": 2}
        swapped = {v: k for k, v in original.items()}
        # ans: {1: 'a', 2: 'b'}
      

Set comprehension


        # basic set comprehension
        squares = {x**2 for x in range(5)}
        # ans: {0, 1, 4, 9, 16}
      

A set removes duplicates


        # auto-removes duplicates
        numbers = [1, 2, 2, 3, 3, 3]
        unique = {x for x in numbers}
        # ans: {1, 2, 3}
      

Set with a condition


        # filter set
        evens = {x for x in range(10) if x % 2 == 0}
        # ans: {0, 2, 4, 6, 8}
      

Exercises

Predict the result, then press โ†’ to run the comprehension and check.

Exercise 1


        # dict comprehension?
        {x: x*2 for x in range(3)}
        # ans: {0: 0, 1: 2, 2: 4}
      

Exercise 2


        # dict from pairs?
        pairs = [("a", 1), ("b", 2)]
        {k: v for k, v in pairs}
        # ans: {'a': 1, 'b': 2}
      

Exercise 3


        # dict with if-else?
        {x: "even" if x % 2 == 0 else "odd"
         for x in range(3)}
        # ans: {0: 'even', 1: 'odd', 2: 'even'}
      

Exercise 4


        # nested dict?
        {i: {j: i*j for j in range(2)}
            for i in range(2)}
        # ans: {0: {0: 0, 1: 0}, 1: {0: 0, 1: 1}}
      

The inner comprehension runs once for each i, building that key's value.

Exercise 5


        # set comprehension duplicates?
        {x % 3 for x in range(10)}
        # ans: {0, 1, 2} (only unique values)
      

Exercise 6


        # set vs list comprehension?
        [x for x in [1,2,2,3]]
        # ans: [1, 2, 2, 3]
        {x for x in [1,2,2,3]}
        # ans: {1, 2, 3}
      

Exercise 7


        # dict filter values?
        d = {"a": 1, "b": 2, "c": 3}
        {k: v for k, v in d.items() if v > 1}
        # ans: {'b': 2, 'c': 3}
      

Exercise 8


        # dict transform values?
        d = {"a": 1, "b": 2}
        {k: v*2 for k, v in d.items()}
        # ans: {'a': 2, 'b': 4}
      

Exercise 9


        # set from string?
        {c for c in "hello"}
        # ans: {'h', 'e', 'l', 'o'}
      

A set has no order, so Python may print these letters in any order.

Exercise 10


        # empty dict vs set?
        {}  # dict
        {x for x in []}  # set()
      

Empty braces always mean an empty dict; an empty set prints as set().

Remember

{k: v for ...}

A colon makes a dict. A repeated key keeps the last value.

{x for ...}

No colon makes a set: duplicates disappear, order is not kept.

if at the end

Filters which items get in.

a if c else b in front

Chooses the value for every item; nothing is filtered out.