Skip to content

Merge Dictionary Assignments

Sourcery refactoring id: merge-dict-assign

Description:

Declare the dictionary with values rather than creating an empty one and assigning to it

Before:

hats_i_own = {}
hats_i_own["panama"] = 1
hats_i_own["baseball_cap"] = 2
hats_i_own["bowler"] = 23

After:

hats_i_own = {"panama": 1, "baseball_cap": 2, "bowler": 23}

Explanation:

When declaring a dictionary and filling it up with values one way that can come naturally is to declare it as empty and then add entries to it.

This can be done in place, shortening the code and making the intent more explicit. Now I just need to glance at one line to see that I'm filling a variable with hats, rather than four.

The same holds true for filling up other collection types like sets and lists.