18. Dictionary comprehension

Here, we want to create two dictionaries; index-to-word i2w and word-to-index w2i. In the discouraged approach, we create two dictionaries, use a for loop, and set the key-value pair with the help of enumerate; there are 5 lines of code. In the encouraged approach, using two lines of code, we can declare and instantiate the dictionaries with a for comprehension.

18.1. Don’t do this

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

18.2. Do this

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