Dictionary Comprehension¶
Sourcery refactoring id: dict-comprehension
¶
Description:¶
Replaces dictionaries created with for
loops with dictionary comprehensions
Before:¶
cubes = {}
for i in range(100):
cubes[i] = i**3
After:¶
cubes = {x: x**3 for x in range(100)}
Explanation:¶
A dictionary comprehension can create the dictionary on one line, cutting out the clutter of declaring an empty dict and then adding items.
Turning three lines of code into one is a definite win - it means less scrolling back and forth when reading methods and helps keep things manageable.
Squeezing code onto one line can make it more difficult to read, but for comprehensions this isn't the case. All of the elements that you need are nicely presented, and once you are used to the syntax it is actually more readable than the for loop version.
Another point is that the assignment is now more of an atomic operation - we're
declaring what cubes
is rather than giving instructions on how to build it.
This makes the code read like more of a narrative, since going forward we will
care more about what cubes
is than the details of its construction.
Finally comprehensions will usually execute more quickly than building the collection in a loop, which is another factor if performance is a consideration.