Create an independent list for each dictionary bucket
A status report needs separate lists for queued and failed jobs. Passing one empty list to dict.fromkeys() makes every key refer to that same list. Appending a queued job then also makes it appear in the failed bucket.
Set up
Tested on Linux with CPython 3.12.14. Use Bash, Python 3.12 or newer, a text editor, and the mktemp, rm and rmdir utilities. No packages or network access are needed. Keep the same terminal open and stop if setup fails. Run without -O so the assertions remain enabled.
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Run the example
Save as independent_buckets.py:
names = ("queued", "failed")
shared = dict.fromkeys(names, [])
shared["queued"].append("job-7")
print("Shared:", shared)
print("Same list:", shared["queued"] is shared["failed"])
buckets = {name: [] for name in names}
buckets["queued"].append("job-7")
assert buckets == {"queued": ["job-7"], "failed": []}
assert buckets["queued"] is not buckets["failed"]
print("Independent:", buckets)
buckets["failed"].append("job-9")
assert buckets["queued"] == ["job-7"]
print("After failure:", buckets)Run:
python3 -B independent_buckets.pyObserved output:
Shared: {'queued': ['job-7'], 'failed': ['job-7']}
Same list: True
Independent: {'queued': ['job-7'], 'failed': []}
After failure: {'queued': ['job-7'], 'failed': ['job-9']}Allocate inside the comprehension
The first dictionary contains one list with two references to it. The identity check confirms the sharing without printing memory addresses. Mutating the list through either key changes what both keys show.
In the comprehension, the empty-list expression runs once for each name. The second append changes only the failed bucket, and the assertions check both contents and object identity. A shallow copy of the first dictionary would preserve its shared list references and would not repair this layout.
Choose sharing deliberately
Use fromkeys() when one shared value is appropriate, such as an immutable placeholder. For independent mutable values, create each value inside a comprehension. The dictionary reference documents this shared-value behavior.
This example assumes distinct bucket names. Repeated names still produce one dictionary entry per unique key. A fresh outer list also does not promise independent nested objects if you later append the same mutable job record to several buckets. Decide whether those records should be shared or copied separately.
Clean up
Remove the saved file and empty scratch directory. If the directory is not empty, inspect its contents before removing anything else.
rm -- independent_buckets.py
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirAcknowledgements
This post was created with assistance from AI.