December 2018
Beginner to intermediate
796 pages
19h 54m
English
Dictionary and set comprehensions work exactly like the list ones, only there is a little difference in the syntax. The following example will suffice to explain everything you need to know:
# dictionary.comprehensions.pyfrom string import ascii_lowercaselettermap = dict((c, k) for k, c in enumerate(ascii_lowercase, 1))
If you print lettermap, you will see the following (I omitted the middle results, you get the gist):
$ python dictionary.comprehensions.py{'a': 1, 'b': 2, ... 'y': 25, 'z': 26}
What happens in the preceding code is that we're feeding the dict constructor with a comprehension (technically, a generator expression, we'll see it in a bit). We tell the dict constructor to make key/value pairs from each tuple ...
Read now
Unlock full access