Compare Duplicate File Inventories with Python Counter

An asset export expects two occurrences of hero.png and one of button.png. The observed manifest contains only one hero entry. Comparing sets says the inventories match because a set discards repeated values. A count comparison can identify the missing occurrence.

These examples use Python 3.10 or later. Each input is a finite iterable of filename strings, with one string per manifest entry. The comparison concerns manifest occurrences; it does not inspect file bytes or establish whether two paths refer to the same physical file.

Reproduce the Lost Duplicate

Run this standalone example:

1
2
3
4
5
6
7
8
9
from collections import Counter

expected = ["hero.png", "hero.png", "button.png"]
observed = ["hero.png", "button.png"]

print(set(expected) == set(observed))
print(Counter(expected) == Counter(observed))
# True
# False

Counter stores each distinct filename as a key and its occurrence count as the value. Input order does not affect count equality. Missing keys read as zero, so a missing filename can be compared without manually initializing it. The official Counter reference describes the counting and arithmetic operations used here.

Report Missing and Extra Occurrences

Save this helper as inventory_diff.py:

1
2
3
4
5
6
7
8
9
from collections import Counter


def compare_inventory(expected, observed):
    expected_counts = Counter(expected)
    observed_counts = Counter(observed)
    missing = expected_counts - observed_counts
    extra = observed_counts - expected_counts
    return missing, extra

Counter subtraction returns a new counter containing only positive differences. The first direction reports expected occurrences that were absent; the reverse direction reports unexpected occurrences. Neither operation modifies its operands.

The helper consumes each input once to build its counts. Pass separate iterators for independent inputs; passing the same one-shot iterator twice leaves the second pass exhausted. Pass a sequence of filenames rather than a single filename string, which would count individual characters. A mapping input initializes counts directly instead of counting keys as repeated records, so keep this helper’s input contract to filename iterables.

Run this beside the helper:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from inventory_diff import compare_inventory

missing, extra = compare_inventory(
    iter(["hero.png", "hero.png", "button.png"]),
    iter(["hero.png", "button.png", "bonus.png", "bonus.png"]),
)
print(sorted(missing.items()))
print(sorted(extra.items()))
print(missing.total(), extra.total())
# [('hero.png', 1)]
# [('bonus.png', 2)]
# 1 2

Sorting the item pairs gives the report a predictable filename order. total() sums occurrence counts; len(extra) would count distinct unexpected filenames, giving one rather than two in this example. The counters retain counts without expanding them into potentially large lists of repeated filenames.

Preserve Signs Only When Needed

The mutating subtract() method has different behavior from the - operator. This standalone example keeps a signed balance where positive means missing and negative means extra:

1
2
3
4
5
6
7
8
9
from collections import Counter

balance = Counter(["hero.png", "hero.png", "button.png"])
result = balance.subtract(["hero.png", "button.png", "bonus.png"])

print(result)
print(sorted(balance.items()))
# None
# [('bonus.png', -1), ('button.png', 0), ('hero.png', 1)]

subtract() changes the existing counter, returns None, and retains zero and negative counts. For the helper’s two positive-only reports, subtraction operators express the desired result directly. If you use a signed balance, inspect its values: a stored zero entry still contributes to its key count and can make the container truthy even when every balance is zero.

Test Counts and Input Boundaries

Save this as test_inventory_diff.py beside the helper and run python test_inventory_diff.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
from collections import Counter
from inventory_diff import compare_inventory

assert compare_inventory([], []) == (Counter(), Counter())
assert compare_inventory(["a", "b", "a"], ["b", "a", "a"]) == (
    Counter(), Counter(),
)
assert compare_inventory(["a", "a"], ["a"]) == (
    Counter({"a": 1}), Counter(),
)
assert compare_inventory([], ["b", "b"]) == (
    Counter(), Counter({"b": 2}),
)

expected = ["a", "a", "b"]
observed = ["a", "c", "c"]
missing, extra = compare_inventory(iter(expected), iter(observed))
assert missing == Counter({"a": 1, "b": 1})
assert extra == Counter({"c": 2})
assert all(count > 0 for count in missing.values())
assert all(count > 0 for count in extra.values())
assert not (missing.keys() & extra.keys())
assert missing.total() - extra.total() == len(expected) - len(observed)
assert expected == ["a", "a", "b"]
assert observed == ["a", "c", "c"]
print("Inventory count checks passed.")

The reorder case verifies that this is a count comparison rather than a sequence comparison. The duplicate cases catch a mistaken conversion to sets. Separate iterator inputs exercise single-pass consumption without depending on list indexing.

Define Filename Identity Before Counting

String equality determines which entries share a count. Hero.png, hero.png, and ./hero.png are different keys here. If the manifest format defines a canonical spelling, normalize both inputs according to that contract before counting. Blindly lowercasing paths can merge names that are distinct on a case-sensitive filesystem.

This report intentionally loses sequence order and entry locations. If the next step must identify the exact bad manifest lines, preserve line numbers separately. Memory grows with the number of distinct filenames, so using iterators avoids retaining the original input lists but does not make counting constant-space. Use this approach when duplicate quantities matter and the distinct-name inventory fits in memory.