5. Dictionary comprehension

Here, we want to create two dictionaries: index-to-word i2w and word-to-index w2i. In the first approach, we build both with a loop. In the second, we use dictionary comprehensions to express the intent more directly.

A comprehension makes it obvious that the result is derived mechanically from another iterable without incremental mutation. That is usually easier to scan because the mapping logic sits next to the dictionary being constructed.

5.1. Don’t do this

1words = ['i', 'like', 'to', 'eat', 'pizza', 'and', 'play', 'tennis']
2
3i2w = {}
4w2i = {}
5for i, word in enumerate(words):
6    i2w[i] = word
7    w2i[word] = i

5.2. Do this

1words = ['i', 'like', 'to', 'eat', 'pizza', 'and', 'play', 'tennis']
2
3i2w = {i: word for i, word in enumerate(words)}
4w2i = {word: i for i, word in enumerate(words)}