Skip to content

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”

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

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

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.