Remove zero and negative counts after a Counter update

Remove zero and negative counts after a Counter update

By Batu. AI assistance was used to prepare this article.

Counter.update() adds incoming values to existing counts rather than replacing them. That means a signed update can leave keys at zero or below zero, and those keys remain stored in the Counter. Unary plus, written +counts, builds a new Counter containing only entries whose counts are positive. Reassigning the variable makes that normalized Counter the current inventory.

from collections import Counter

counts = Counter({"apples": 2, "bananas": 1, "dates": 0})
counts.update({"apples": -2, "bananas": 3, "carrots": -1})

before = dict(counts)
counts = +counts

after = dict(counts)
assert before == {"apples": 0, "bananas": 4, "dates": 0, "carrots": -1}
assert after == {"bananas": 4}
assert list(counts) == ["bananas"]

print(f"before={before}")
print(f"after={after}")

Expected stdout

before={'apples': 0, 'bananas': 4, 'dates': 0, 'carrots': -1}
after={'bananas': 4}

The incoming mapping decreases apples to zero, adds three to bananas, and introduces carrots with a negative count. The source dates key was already zero. After unary plus, only bananas: 4 survives. This is concise because it avoids deleting keys while iterating over the Counter.

Normalization changes the meaning of signed data. Do not apply unary plus if a negative count represents a debt, correction, or backorder that must remain observable. It also returns a new object rather than mutating counts in place, so omitting the assignment leaves the original entries untouched. Counter keys still need to be hashable, and the values used by update() must support addition. When supplying an iterable to update(), its items are treated as keys; use a mapping, as in this example, to add explicit signed increments.

Source: Python Counter documentation.

Comments

Popular posts from this blog

Compare Two Text Files in Python Without Modifying Them

Seven CSV Quality Checks to Run Before Importing Data

Explain why SQLite transactions cannot make an HTTP call atomic