This rule raises an issue when a dictionary comprehension is used to create a dictionary where all values are the same constant.

Why is this an issue?

Using a dictionary comprehension to build a dictionary where every key maps to the exact same constant value e.g., {k: 1 for k in keys} is less efficient and less idiomatic than using the dict.fromkeys() class method. dict.fromkeys() is specifically designed for this use case and offers better performance, especially for large iterables, as it avoids the overhead of creating and processing individual key-value pairs in a comprehension.

How to fix it

Rewrite the dictionary comprehension {x: constant for x in iterable} as dict.fromkeys(iterable, constant). If the constant value is None, you can omit the value argument in dict.fromkeys(), as it defaults to None.

Code examples

Noncompliant code example

keys = ['a', 'b', 'c']

dict_comp_one = {k: 1 for k in keys} # Noncompliant

Compliant solution

keys = ['a', 'b', 'c']

dict_fromkeys_one = dict.fromkeys(keys, 1)

Resources

Documentation