Avoid Duplicate Dict Keys

ID

python.avoid_duplicate_keys

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Python

Tags

reliability, suspicious-construct

Description

Reports dict literals with two or more entries sharing the same literal key. Python evaluates the entries left to right and silently keeps the last value, so the earlier entries are dead weight — almost always a copy-paste mistake.

config = {
    "host": "a",
    "port": 5432,
    "host": "b",          # FLAW — overwrites the first "host"
}

Rationale

There is no warning at parse time and no error at runtime. The only signal is the constructed dict missing whatever value the earlier entry contributed, which surfaces far from the literal as a "why is host always b?" puzzle.

Remediation

Fix the typo, drop the duplicate, or restructure the dict if the values were meant to be merged.

Notes

The rule fires only when both keys are syntactically literal (string, number, None, True, False). Computed keys ({f(): 1, f(): 2}) are not detected — they may produce different values at runtime. Likewise, two string keys with the same logical content but different quote styles ("x" vs 'x') are flagged because their source representation matches after trimming.