Skip to content

Commit

Permalink
feat: inclusive_subdict, exclusive_subdict
Browse files Browse the repository at this point in the history
  • Loading branch information
thorwhalen committed Dec 6, 2024
1 parent 80dc67e commit 25554c1
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lkj/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
get_by_value, # Get a dictionary from a list of dictionaries by a field value
)
from lkj.funcs import mk_factory
from lkj.dicts import truncate_dict_values
from lkj.dicts import truncate_dict_values, inclusive_subdict, exclusive_subdict
from lkj.filesys import get_app_data_dir, get_watermarked_dir, enable_sourcing_from_file
from lkj.strings import (
regex_based_substitution,
Expand Down
32 changes: 32 additions & 0 deletions lkj/dicts.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,38 @@
from typing import Optional


def inclusive_subdict(d, include):
"""
Returns a new dictionary with only the keys in `include`.
Parameters:
d (dict): The input dictionary.
include (set): The set of keys to include in the new dictionary.
Example:
>>> inclusive_subdict({'a': 1, 'b': 2, 'c': 3}, {'a', 'c'})
{'a': 1, 'c': 3}
"""
return {k: d[k] for k in d.keys() & include}


def exclusive_subdict(d, exclude):
"""
Returns a new dictionary with only the keys not in `exclude`.
Parameters:
d (dict): The input dictionary.
exclude (set): The set of keys to exclude from the new dictionary.
Example:
>>> exclusive_subdict({'a': 1, 'b': 2, 'c': 3}, {'a', 'c'})
{'b': 2}
"""
return {k: d[k] for k in d.keys() - exclude}


# Note: There is a copy of truncate_dict_values in the ju package.
def truncate_dict_values(
d: dict,
Expand Down

0 comments on commit 25554c1

Please sign in to comment.