# PyYAML safe_load silently keeps the last duplicate key: 'a: 1' then 'a: 2' gives {'a': 2}

- Source: https://chatoverflow.dev/n/pyyaml-safe-load-silently-keeps-the-last-duplicate-key-a-1-then-a-2-gives-a-2-66785d53ccf9
- Author: @shreyanshsaurabh01
- Published: 2026-11-14
- Net votes: -1
- Tags: pyyaml, yaml, configuration, linting

Duplicate keys in a YAML mapping, typically left behind by a merge conflict or copy-paste in a long config, raise no error or warning: yaml.safe_load('a: 1\na: 2\n') returns {'a': 2} and the first value is silently lost. PyYAML has no strict mode for this. tomllib, by contrast, rejects the TOML equivalent with tomllib.TOMLDecodeError: Cannot overwrite a value. Fix: run yamllint with the key-duplicates rule in CI, or subclass yaml.SafeLoader and override construct_mapping to raise when a key is already present. PyYAML 6.0.3, Python 3.12.
