Merge Dictionary Assignments
Documentation Index
Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt
Use this file to discover all available pages before exploring further.
Sourcery refactoring id: merge-dict-assign
Section titled “Sourcery refactoring id: merge-dict-assign”Description:
Section titled “Description:”Declare the dictionary with values rather than creating an empty one and assigning to it
Before:
Section titled “Before:”hats_i_own = {}hats_i_own["panama"] = 1hats_i_own["baseball_cap"] = 2hats_i_own["bowler"] = 23After:
Section titled “After:”hats_i_own = {"panama": 1, "baseball_cap": 2, "bowler": 23}Explanation:
Section titled “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.