Skip to content

Dict Tools

Functions for manipulating dictionaries.


convert_key_case

convert_key_case(data, key_case)

Recursively convert dictionary keys using a case-conversion function.

Parameters:

Name Type Description Default
data T

A dict, list, or scalar value.

required
key_case Callable[[str], str]

A callable that transforms string keys (e.g., snakecase).

required

Returns:

Type Description
T

A copy of data with all dictionary keys transformed.

Source code in src/aibs_informatics_core/utils/tools/dicttools.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
def convert_key_case(data: T, key_case: Callable[[str], str]) -> T:
    """Recursively convert dictionary keys using a case-conversion function.

    Args:
        data: A dict, list, or scalar value.
        key_case: A callable that transforms string keys (e.g., ``snakecase``).

    Returns:
        A copy of ``data`` with all dictionary keys transformed.
    """
    if isinstance(data, dict):
        return {
            (key_case(k) if isinstance(k, str) else k): convert_key_case(v, key_case)
            for k, v in data.items()
        }  # type: ignore
    elif isinstance(data, list):
        return [convert_key_case(item, key_case) for item in data]  # type: ignore
    else:
        return data

flatten_dict

flatten_dict(data, parent_key='', delimiter='.')

Flattens a nested dictionary by concatenating the keys with a given delimiter.

Args: data (Dict[str, Any]): The dictionary to flatten. parent_key (str, optional): The concatenated key for the nested items. Defaults to ''. delimiter (str, optional): The delimiter to use for concatenating the keys. Defaults to '.'.

Returns: Dict[str, Any]: The flattened dictionary.

Source code in src/aibs_informatics_core/utils/tools/dicttools.py
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
def flatten_dict(
    data: MutableMapping[str, Any], parent_key: str = "", delimiter: str = "."
) -> dict[str, Any]:
    """
    Flattens a nested dictionary by concatenating the keys with a given delimiter.

    Args:
    data (Dict[str, Any]): The dictionary to flatten.
    parent_key (str, optional): The concatenated key for the nested items. Defaults to ''.
    delimiter (str, optional): The delimiter to use for concatenating the keys. Defaults to '.'.

    Returns:
    Dict[str, Any]: The flattened dictionary.
    """
    items: list[tuple[str, Any]] = []
    for key, value in data.items():
        new_key = f"{parent_key}{delimiter}{key}" if parent_key else key
        if isinstance(value, dict):
            items.extend(flatten_dict(value, new_key, delimiter).items())
        else:
            items.append((new_key, value))
    return dict(items)

nested_dict

nested_dict(data, delimiter='.')

Creates a nested dictionary by splitting the keys by a given delimiter.

Args: data (Dict[str, Any]): The dictionary to transform. delimiter (str, optional): The delimiter to use for splitting the keys. Defaults to '.'.

Returns: Dict[str, Any]: The transformed, nested dictionary.

Raises: ValueError: If a collision is detected during the transformation process.

Source code in src/aibs_informatics_core/utils/tools/dicttools.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
def nested_dict(data: MutableMapping[str, Any], delimiter: str = ".") -> dict[str, Any]:
    """
    Creates a nested dictionary by splitting the keys by a given delimiter.

    Args:
    data (Dict[str, Any]): The dictionary to transform.
    delimiter (str, optional): The delimiter to use for splitting the keys. Defaults to '.'.

    Returns:
    Dict[str, Any]: The transformed, nested dictionary.

    Raises:
    ValueError: If a collision is detected during the transformation process.
    """
    result: dict[str, Any] = {}
    for key, value in data.items():
        parts = key.split(delimiter)
        d = result
        for part in parts[:-1]:
            if part not in d:
                d[part] = {}
            elif not isinstance(d[part], dict):
                raise ValueError(f"Key collision detected at '{part}' when processing '{key}'")
            d = d[part]
        if parts[-1] in d and d[parts[-1]] != value:
            raise ValueError(f"Key collision detected at '{parts[-1]}' when processing '{key}'")
        d[parts[-1]] = value
    return result

remove_matching_values

remove_matching_values(
    orig_dict,
    in_place=False,
    recursive=False,
    target_value=None,
)

Filter out keys with values matching target value

Parameters:

Name Type Description Default
orig_dict MutableMapping[KT, VT]

Original dictionary

required
in_place bool

If true, removes keys in place. Defaults to False.

False
recursive bool

If true, recursively removes values if target value. Defaults to False.

False

Returns:

Type Description
MutableMapping[KT, VT]

MutableMapping[KT, VT]: dictionary without target values

Source code in src/aibs_informatics_core/utils/tools/dicttools.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
def remove_matching_values(
    orig_dict: MutableMapping[KT, VT],
    in_place: bool = False,
    recursive: bool = False,
    target_value: Any = None,
) -> MutableMapping[KT, VT]:
    """Filter out keys with values matching target value

    Args:
        orig_dict (MutableMapping[KT, VT]): Original dictionary
        in_place (bool, optional): If true, removes keys in place. Defaults to False.
        recursive (bool, optional): If true, recursively removes values if target value.
            Defaults to False.

    Returns:
        MutableMapping[KT, VT]: dictionary without target values
    """
    filtered_dict = orig_dict if in_place else deepcopy(orig_dict)

    for k, v in list(filtered_dict.items()):
        if isinstance(v, dict) and recursive:
            filtered_dict[k] = cast(VT, remove_null_values(v, in_place=True, recursive=recursive))
        elif v == target_value:
            filtered_dict.pop(k)
    return filtered_dict

remove_null_values

remove_null_values(
    orig_dict, in_place=False, recursive=False
)

Removes null values from a dictionary object

Parameters:

Name Type Description Default
orig_dict MutableMapping[KT, VT]

target dictionary to prune null values from

required
in_place bool

whether to do operation on target in place. Defaults to False.

False
recursive bool

whether to prune recursively. Defaults to False.

False

Returns:

Type Description
MutableMapping[KT, VT]

MutableMapping[KT, VT]: pruned dictionary

Source code in src/aibs_informatics_core/utils/tools/dicttools.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
def remove_null_values(
    orig_dict: MutableMapping[KT, VT],
    in_place: bool = False,
    recursive: bool = False,
) -> MutableMapping[KT, VT]:
    """Removes null values from a dictionary object

    Args:
        orig_dict (MutableMapping[KT, VT]): target dictionary to prune null values from
        in_place (bool, optional): whether to do operation on target in place. Defaults to False.
        recursive (bool, optional): whether to prune recursively. Defaults to False.

    Returns:
        MutableMapping[KT, VT]: pruned dictionary
    """
    return remove_matching_values(
        orig_dict=orig_dict, in_place=in_place, recursive=recursive, target_value=None
    )