Files
saladeaula.digital/layercake/layercake/funcs.py
2025-04-12 21:04:02 -03:00

63 lines
1.5 KiB
Python

from typing import Any
def pick(
keys: list[str] | tuple[str, ...],
dct: dict[str, Any],
exclude_none: bool = True,
default: Any = None,
) -> dict[str, Any]:
"""
Return a partial dict with only the specified keys.
Parameters
----------
keys: list[str] or tuple[str, ...]
Keys to select.
dct: dict[str, Any]
Source dict.
exclude_none: bool, optional
If True, omit keys not in dct; if False, include them with `default`.
default: Any, optional
Value for keys not in dct when exclude_none is False.
Returns
-------
dict[str, Any]
A dict with the picked key/value pairs.
Examples
--------
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> pick(['a', 'c'], d)
{'a': 1, 'c': 3}
>>> pick(['a', 'd'], d, exclude_none=False, default='missing')
{'a': 1, 'd': 'missing'}
"""
return {k: dct.get(k, default) for k in keys if k in dct or not exclude_none}
def omit(keys: list[str] | tuple[str, ...], dct: dict[str, Any]) -> dict[str, Any]:
"""
Return a partial dict omitting the specified keys.
Parameters
----------
keys: list[str] or tuple[str, ...]
Keys to omit.
dct: dict[str, Any]
Source dict.
Returns
-------
dict[str, Any]
A dict without the omitted key/value pairs.
Examples
--------
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> omit(['b'], d)
{'a': 1, 'c': 3}
"""
return {k: dct[k] for k in dct.keys() if k not in keys}