Dictionary Comprehension

Python pattern

Replaces dictionaries created with for loops with dictionary comprehensions.


Apply with the Grit CLI
grit apply dict_comprehension

Dictionary comprehension

BEFORE
cubes = {}
for i in range(100):
    cubes[i] = i**3
cubes = {}
for i in range(100):
    cubes[i*2] = i**3
cubes = {1: 2}
for i in range(100):
    cubes[i*2] = i**3
AFTER
cubes = {i: i**3 for i in range(100)}
cubes = {i*2: i**3 for i in range(100)}
cubes = {1: 2}
for i in range(100):
    cubes[i*2] = i**3