Avoid Shared Python Group Lists with Dictionary Comprehensions

An asset report groups filenames into ready and failed buckets. After appending one ready filename, the failed bucket mysteriously contains it too. The keys are different, but both values refer to the same list. This is easy to introduce when initializing a dictionary with dict.fromkeys().

These examples use Python 3.10 or later and ordinary string keys. The report keeps the original filename order within each bucket and retains empty buckets so consumers receive a consistent shape.

Reproduce the Shared List

Run this standalone example:

1
2
3
4
5
6
7
buckets = dict.fromkeys(("ready", "failed"), [])
buckets["ready"].append("hero.png")

print(buckets)
print(buckets["ready"] is buckets["failed"])
# {'ready': ['hero.png'], 'failed': ['hero.png']}
# True

The [] expression creates one list before the call. fromkeys() uses that same value for every key; it does not call a list factory for each entry. Python documents this behavior in the dict.fromkeys reference .

Use is to diagnose sharing. Two separate empty lists compare equal with ==, so equality alone cannot establish whether later mutations will remain isolated.

Allocate Each Known Bucket Separately

Save this helper as asset_groups.py:

1
2
3
4
5
6
7
def group_assets(records):
    buckets = {status: [] for status in ("ready", "failed")}
    for status, filename in records:
        if status not in buckets:
            raise ValueError(f"unknown asset status: {status!r}")
        buckets[status].append(filename)
    return buckets

The comprehension evaluates [] on each iteration. Creating the dictionary inside the function also gives separate calls separate containers. The function accepts a finite iterable of two-item records, consumes it once, and returns a complete dictionary. It rejects unexpected status strings rather than silently expanding the report schema.

Run this beside the helper:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from asset_groups import group_assets

report = group_assets(iter([
    ("ready", "hero.png"),
    ("failed", "broken.png"),
    ("ready", "button.png"),
]))
print(report)
print(group_assets([]))
# {'ready': ['hero.png', 'button.png'], 'failed': ['broken.png']}
# {'ready': [], 'failed': []}

This groups by status across the complete input, including nonadjacent records. It keeps duplicates, and it does not sort filenames. An exception prevents a partial dictionary from being returned, although records already pulled from a source iterator have still been consumed.

Test Mutation Isolation Directly

Save this as test_asset_groups.py beside the helper and run python test_asset_groups.py:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from asset_groups import group_assets

first = group_assets([])
second = group_assets([])
assert first == second == {"ready": [], "failed": []}
assert first["ready"] is not first["failed"]
assert first["ready"] is not second["ready"]

first["ready"].append("hero.png")
assert first["failed"] == []
assert second == {"ready": [], "failed": []}

records = [
    ("failed", "broken.png"),
    ("ready", "hero.png"),
    ("failed", "broken.png"),
]
assert group_assets(iter(records)) == {
    "ready": ["hero.png"],
    "failed": ["broken.png", "broken.png"],
}

try:
    group_assets([("queued", "later.png")])
except ValueError as exc:
    assert "queued" in str(exc)
else:
    raise AssertionError("unknown status was accepted")

print("Asset group isolation checks passed.")

These checks deliberately mutate a returned list. A test that only compares initially empty dictionaries would pass even if every bucket shared a single empty list. Testing a second call also catches accidental state stored outside the function.

Use a Factory for Discovered Keys

For reports whose statuses are intentionally discovered from input, a defaultdict(list) can allocate missing buckets. This is a different contract from the fixed two-bucket helper:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from collections import defaultdict

buckets = defaultdict(list)
for status, filename in [("queued", "later.png"), ("ready", "hero.png")]:
    buckets[status].append(filename)

assert buckets["queued"] is not buckets["ready"]
assert buckets.get("missing") is None
assert "missing" not in buckets
print(dict(buckets))
# {'queued': ['later.png'], 'ready': ['hero.png']}

Pass the callable list, which creates a fresh list when a missing key is accessed with buckets[key]. The defaultdict documentation also distinguishes this access from get(), which does not invoke the factory. Reading a missing bucket with square brackets inserts it, so use membership checks or get() when inspection should preserve the key set.

Define How Far Isolation Extends

Independent bucket lists do not imply independent record objects. The fixed helper appends filename strings, which are immutable. If a variant appends mutable dictionaries instead, it stores references to those dictionaries. Updating a record through one reference will remain visible through another unless the application explicitly copies it.

Likewise, copying the outer dictionary with buckets.copy() leaves its list values shared with the original. Decide which layer owns each mutable object, then test mutations at that layer. For this report, the required boundary is concrete: every status owns its list, and every function call owns a fresh report.