Use comprehensions for deleting from dictionaries

Python pattern

Replaces cases where deletions are made via for loops with comprehensions.


Apply with the Grit CLI
grit apply del_comprehension

Delete comprehension

BEFORE
x1 = {"a": 1, "b": 2, "c": 3}
for key in x1.copy():  # can't iterate over a variable that changes size
    if key not in x0:
        del x1[key]

for key in x0:
    del x1[key]
AFTER
x1 = {"a": 1, "b": 2, "c": 3}
x1 = {key: value for key, value in x1.items() if key in x0}

for key in x0:
    del x1[key]