Skip to content

utils

add_kv_to_dict(d, k, v, as_list=False)

Add a key-value pair to a dictionary.

Parameters:

Name Type Description Default
d dict[str, Any]

Dictionary to add the key-value pair to.

required
k str

Key to add.

required
v Any

Value to add.

required
as_list bool

If True, the value is appended to the list identified by k.

False

Returns:

Type Description
dict[str, Any]

Dictionary with the key-value pair added. If the key already exists,

dict[str, Any]

the value is saved as a list.

Source code in metabolike/utils.py
def add_kv_to_dict(d: dict[str, Any], k: str, v: Any, as_list: bool = False) -> dict[str, Any]:
    """Add a key-value pair to a dictionary.

    Args:
        d: Dictionary to add the key-value pair to.
        k: Key to add.
        v: Value to add.
        as_list: If True, the value is appended to the list identified by `k`.

    Returns:
        Dictionary with the key-value pair added. If the key already exists,
        the value is saved as a list.
    """
    k_camel = snake_to_camel(k)
    if as_list:
        d.setdefault(k_camel, []).append(v)
    else:
        d[k_camel] = v

    return d

chunk(itr, chunk_size)

Chunk an iterator into chunks of size chunk_size.

Ref: https://stackoverflow.com/a/71572942/5925357

Source code in metabolike/utils.py
def chunk(itr: Iterable, chunk_size: int) -> Iterable:
    """Chunk an iterator into chunks of size chunk_size.

    Ref: https://stackoverflow.com/a/71572942/5925357
    """
    itr = iter(itr)
    while slice_ := list(islice(itr, chunk_size)):
        yield slice_

snake_to_camel(s, sep='-')

Convert snake_case to CamelCase.

Parameters:

Name Type Description Default
s str

String to convert.

required
sep str

Separator to use.

'-'

Returns:

Type Description
str

camelCase string.

Source code in metabolike/utils.py
def snake_to_camel(s: str, sep: str = "-") -> str:
    """Convert snake_case to CamelCase.

    Args:
        s: String to convert.
        sep: Separator to use.

    Returns:
        camelCase string.
    """
    s_camel = [x.capitalize() for x in s.split(sep)]
    s_camel[0] = s_camel[0].lower()
    return "".join(s_camel)