Use list and dict comprehension instead

Using list and dict comprehension is simpler and computationally quicker than calling list() and dict().

Comprehensions are more efficient than calling dict() and list().

Given that these are completely equivalent:

Why not choose the easiest to both read, write, and quickest to execute (the first one)?

Do not follow this advice with set comprehension though, as when set comprehension is performed on an empty iterable it returns a dict because Python cannot differentiate set comprehension and dict comprehension when working with an empty iterable:

Notice that four evaluated to an empty dict, which was unwanted behaviour.

If our GitHub code review bot spots this issue in your pull request it gives this advice:

code-review-doctorbotsuggested changes just now
helpers.py
1
+
dict((item, get_value(item)) for item in items)
Suggested changes
-
dict((item, get_value(item)) for item in items)
+
{item: get_value(item) item item in items}
Commit suggestion

Using list and dict comprehension is simpler and computationally quicker than calling list() and dict().

Read more
Update helpers.py
We're your Python code review copilot. Get code improvements right in your pull request with our GitHub code review bot.

Configuring this check

Code Review Doctor will run this check by default. No configuration is needed but the check can be turned on/off using check code use-comprehension in your pyproject.toml file.

Read more about configuring Code Review Doctor.