Two variable dictionary comprehension

Steve D'Aprano steve+python at
Mon Apr 3 21:04:34 EDT 2017

On Tue, 4 Apr 2017 03:27 am, Deborah Swanson wrote:

> I'll admit that both dictionaries and comprehensions are still a little
> bit fuzzy to me, especially when I get away from the common usages. This
> could be a good exercise to clarify some of the fuzzy areas.

As far as comprehensions go, how is your mathematics?

If you remember your set builder notation from maths, list comprehensions
are based on that.

In maths, we say something like:

{2n + 1 : 0 ≤ n ≤ 9}

which might be read aloud as "the set of 2 times n, plus 1, such that n is
between 0 and 9 inclusive".

A similar notation might be:

{2n + 1 : n ∈ {1, 2, 3}}

said as "the set of 2 times n, plus 1, such that n is an element of the set
{1, 2, 3}".

If you're a maths geek like me, this is second nature :-)

Now, Python's list comprehension syntax is based on a similar notation,
except we spell it out in words rather than symbols, using the
familiar "for n in ..." syntax from for-loops instead of : "such that".

{2*n + 1 for n in range(10)}

{2*n + 1 for n in (1, 2, 3)}

A few other differences:

- list comprehensions use [ ] for the outermost brackets;
- set and dict comprehensions use { };
- generator expressions use ( ) (unless the parentheses can be implied).

We're not restricted to mathematical expressions, and can use any Python
expression we like:

[value.method(arg)[1] for (value, arg) in zip(values, arguments)]

translates roughly into this for-loop:

result = []
for (value, arg) in zip(values, arguments):

Another difference is that comprehensions allow an "if" clause:

[v.method(a)[1] for (v, a) in zip(values, arguments) if v is not None]

translates something like:

result = []
for (v, a) in zip(values, arguments):
    if v is not None:

There's more, but that covers probably 98% of comprehension usage.

And of course, remember that dict comprehensions use the same key:value
syntax as ordinary dict "literals" (the official name is "dict display").

result = {}
for key, value in zip(keys, values):
    result[key] = value


result = {key:value for (key, value) in zip(keys, values)}

although frankly that's better written as:

dict(zip(keys, values))

Hope this helps!

“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

More information about the Python-list mailing list