dict.fromkeys Shares One Mutable Default

dict.fromkeys binds every key to the same mutable object, so appending through one key mutates all rows; a comprehension builds an independent container.

PythonData Integrity

Code

pythonsnippet
16 lines
keys = ["alpha", "beta", "gamma"]

# dangerous: every key shares the same list object
table = dict.fromkeys(keys, [])
table["alpha"].append(1)
print("aliased:", table)

# safe: a comprehension builds an independent container per key
safe = {key: [] for key in keys}
safe["alpha"].append(1)
print("independent:", safe)

# immutable defaults carry no aliasing problem, so fromkeys remains appropriate there
widths = dict.fromkeys(keys, 0)
widths["beta"] += 3
print("widths:", widths)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

aliased: {'alpha': [1], 'beta': [1], 'gamma': [1]}
independent: {'alpha': [1], 'beta': [], 'gamma': []}
widths: {'alpha': 0, 'beta': 3, 'gamma': 0}

How it works

The file’s state is a handful of top-level bindings: keys, table, safe, widths.

Watch out for

  • No third-party packages are used — the runtime ships every API called here.

Using it in your own code

Look for the aliased:, independent:, widths: prefixes as the file executes; they connect every printed line to the step behind it.

Interactive Tools for This Topic

FAQ

Will the snippet run without installing packages?
Yes, it runs as-is — nothing outside the built-in APIs is referenced. Its state lives in module-level bindings: `keys`, `table`, `safe`.