This rule raises an issue when a dictionary comprehension uses a static key.
Dictionary comprehensions are a concise way to create dictionaries, typically by dynamically generating key-value pairs during iteration. When the
key part of a dictionary comprehension is static (e.g., a string literal like "key" or a variable defined outside the comprehension that
isn’t updated during the comprehension), each iteration of the comprehension will attempt to assign a value to this same single
key.
The consequence is that the dictionary will only contain one entry for that static key, and its value will be the one computed during the last iteration of the comprehension. This behavior is often a misunderstanding of how dictionary comprehensions work or a logical error, as the intention is usually to create multiple distinct key-value pairs.
Consider this example:
data = ["apple", "banana", "cherry"]
# Each iteration overwrites the value associated with "fruit_type"
result_dict = {"fruit_type": value.capitalize() for value in data}
# After the first iteration: {"fruit_type": "Apple"}
# After the second iteration: {"fruit_type": "Banana"}
# Final result: {"fruit_type": "Cherry"}
In the code above, the loop iterates three times, but because "fruit_type" is always the same key, the final dictionary
result_dict will only be {'fruit_type': 'CHERRY'}. All previous assignments for this key are overwritten. This is usually
not what the developer intends when using a comprehension over data.
If the goal was to have multiple distinct keys, the key expression in the comprehension must vary with each iteration.
To fix this issue ensure that the key expression within the dictionary comprehension is dynamic, meaning it changes with each iteration, typically by using the iteration variable(s). This ensures that unique keys are generated, leading to a dictionary with multiple entries as usually intended.
data = ["some", "Data"]
output_dict = {"key": value.upper() for value in data} # Noncompliant: "key" is not modify for each iteration
data = ["some", "Data"]
output_dict = {value: value.upper() for value in data} # Compliant