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.