Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion kv/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from kv.count_prefix import count_prefix
from kv.count_values import count_values
from kv.key_count_with_value import key_count_with_value
from kv.filter_prefix import filter_prefix
from kv.has_all import has_all
from kv.invert import invert
Expand All @@ -14,4 +15,4 @@
from kv.sorted_keys import sorted_keys
from kv.values_with_prefix import values_with_prefix

__all__ = ["count_prefix", "count_values", "filter_prefix", "has_all", "invert", "max_value_key", "merge", "min_key", "omit", "pick", "rename_key", "sorted_keys", "values_with_prefix"]
__all__ = ["count_prefix", "count_values", "key_count_with_value", "filter_prefix", "has_all", "invert", "max_value_key", "merge", "min_key", "omit", "pick", "rename_key", "sorted_keys", "values_with_prefix"]
8 changes: 8 additions & 0 deletions kv/key_count_with_value.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
def key_count_with_value(m: dict[str, str], value: str) -> int:
"""Count keys whose value equals the given value.

Returns 0 for an empty dict.
"""
if not m:
return 0
return sum(1 for v in m.values() if v == value)
30 changes: 30 additions & 0 deletions kv/test_key_count_with_value.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
from kv.key_count_with_value import key_count_with_value


def test_empty_dict():
"""Empty dict returns 0."""
assert key_count_with_value({}, "any") == 0


def test_no_match():
"""No keys have the target value."""
m = {"a": "1", "b": "2", "c": "3"}
assert key_count_with_value(m, "4") == 0


def test_several_matches():
"""Several keys have the target value."""
m = {"a": "x", "b": "y", "c": "x", "d": "x"}
assert key_count_with_value(m, "x") == 3


def test_single_match():
"""Single key has the target value."""
m = {"a": "1", "b": "2", "c": "3"}
assert key_count_with_value(m, "2") == 1


def test_all_match():
"""All keys have the target value."""
m = {"a": "same", "b": "same", "c": "same"}
assert key_count_with_value(m, "same") == 3