Skip to content

Util Methods Module

filter_dicts_by_values(raw_dicts, filter_value, keep=None, drop=None)

Filters a list of dicts based whether contain a specific value.

Parameters:

Name Type Description Default
raw_dicts List[Dict]

The list of dicts to filter.

required
filter_value str | List | None

The value or a list of values to filter by. Can be None if you want to drop all dictionaries with empty values.

required
keep bool | None

Whether to keep the dictionaries that contain the filter_value. Defaults to None.

None
drop bool | None

Whether to exclude the dictionaries that contain the filter_value. Defaults to None.

None

Raises:

Type Description
ValueError

If keep and drop are None, raises: keep and drop cannot be both None.

ValueError

If keep and drop are True, raises: keep and drop cannot be both True.

ValueError

If keep and drop are False, raises: keep and drop cannot be both False.

TypeError

If keep is True or drop is False andfilter_value isn't a str or a list, raises: To keep the filter_value it must be a str or a list.

TypeError

If keep is False or drop is True and filter_value isn't a str, list or None, raises: filter_value must be a str, list or None.

Returns:

Type Description
List[Dict]

List[Dict]: The filtered list of dictionaries.

Examples:

>>> filter_dicts_by_values([{"A": "1", "B": "2"}, {"C": "3", "D": "4"}], filter_value="3", keep=False)
[{'A': '1', 'B': '2'}]
>>> filter_dicts_by_values([{"A": "1", "B": "2"}, {"C": "3", "D": "4"}], filter_value="3", keep=True)
[{'C': '3', 'D': '4'}]
>>> filter_dicts_by_values([{"A": "1", "B": "2"}, {"C": "3", "D": "4"}], filter_value="3", drop=False)
[{'C': '3', 'D': '4'}]
>>> filter_dicts_by_values([{"A": "1", "B": "2"}, {"C": "3", "D": "4"}], filter_value="3", drop=True)
[{'A': '1', 'B': '2'}]
Source code in carol_app_monitor/utils.py
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 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
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 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
118
119
120
121
def filter_dicts_by_values(
    raw_dicts: List[Dict],
    filter_value: str | List | None,
    keep: bool | None = None,
    drop: bool | None = None,
) -> List[Dict]:
    """Filters a list of dicts based whether contain a specific value.

    Args:
        raw_dicts (List[Dict]): The list of dicts to filter.
        filter_value (str | List | None): The value or a list of values to filter by.\
        Can be `None` if you want to drop all dictionaries with empty values.

        keep (bool | None, optional): Whether to keep the dictionaries that\
        contain the `filter_value`. Defaults to None.

        drop (bool | None, optional): Whether to exclude the dictionaries that\
        contain the `filter_value`. Defaults to None.

    Raises:
        ValueError: If `keep` and `drop` are `None`, raises: keep and drop\
        cannot be both None.
        ValueError: If `keep` and `drop` are `True`, raises: keep and drop\
        cannot be both True.
        ValueError: If `keep` and `drop` are `False`, raises: keep and drop\
        cannot be both False.
        TypeError: If `keep` is `True` or `drop` is `False` and`filter_value`\
        isn't a `str` or a `list`, raises: To keep the `filter_value` it must\
        be a `str` or a `list`.
        TypeError: If `keep` is `False` or `drop` is `True` and `filter_value`\
        isn't a `str`, `list` or `None`, raises: filter_value must be a str, list\
        or None.

    Returns:
        List[Dict]: The filtered list of dictionaries.

    Examples:
        >>> filter_dicts_by_values([{"A": "1", "B": "2"}, {"C": "3", "D": "4"}], filter_value="3", keep=False)
        [{'A': '1', 'B': '2'}]

        >>> filter_dicts_by_values([{"A": "1", "B": "2"}, {"C": "3", "D": "4"}], filter_value="3", keep=True)
        [{'C': '3', 'D': '4'}]

        >>> filter_dicts_by_values([{"A": "1", "B": "2"}, {"C": "3", "D": "4"}], filter_value="3", drop=False)
        [{'C': '3', 'D': '4'}]

        >>> filter_dicts_by_values([{"A": "1", "B": "2"}, {"C": "3", "D": "4"}], filter_value="3", drop=True)
        [{'A': '1', 'B': '2'}]
    """
    if keep is None and drop is None:
        raise ValueError("`keep` and `drop` cannot be both `None`.")

    if keep and drop:
        raise ValueError("`keep` and `drop` cannot be both `True`.")

    if keep is False and drop is False:
        raise ValueError("`keep` and `drop` cannot be both `False`.")

    match keep, drop:
        case [True, False] | [True, None] | [None, False]:
            if isinstance(filter_value, str):
                filtered_dicts = [
                    raw_dict
                    for raw_dict in raw_dicts
                    if filter_value in raw_dict.values()
                ]
            elif isinstance(filter_value, list):
                filtered_dicts = [
                    raw_dict
                    for raw_dict in raw_dicts
                    if _check_intersection(filter_value, raw_dict.values())
                ]
            else:
                raise TypeError(
                    "To keep the `filter_value` it must be a `str` or a `list`."
                )

        case [False, True] | [None, True] | [False, None]:
            if isinstance(filter_value, (str, type(None))):
                filtered_dicts = [
                    raw_dict
                    for raw_dict in raw_dicts
                    if filter_value not in raw_dict.values()
                ]
            elif isinstance(filter_value, list):
                filtered_dicts = [
                    raw_dict
                    for raw_dict in raw_dicts
                    if not _check_intersection(filter_value, raw_dict.values())
                ]
            else:
                raise TypeError(
                    "`filter_value` must be a `str`, `list` or `None`."
                )

    return filtered_dicts

merge_dicts(*dicts)

Merge dicts into unique dict.

Raises:

Type Description
TypeError

If any args aren't a dict, raises: Args must be a dict.

Returns:

Name Type Description
Dict Dict

Merged dict.

Examples:

>>> merge_dicts({"A": 1, "B": 2},{"C": 3, "D": 4})
{'A': 1, 'B': 2, 'C': 3, 'D': 4}
Source code in carol_app_monitor/utils.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def merge_dicts(*dicts: Dict) -> Dict:
    """Merge dicts into unique dict.

    Raises:
        TypeError: If any args aren't a dict, raises:\
        Args must be a `dict`.

    Returns:
        Dict: Merged dict.

    Examples:
        >>> merge_dicts({"A": 1, "B": 2},{"C": 3, "D": 4})
        {'A': 1, 'B': 2, 'C': 3, 'D': 4}
    """
    merged_dicts = {}

    for raw_dict in dicts:
        if not isinstance(raw_dict, dict):
            raise TypeError("Args must be `dict`.")
        merged_dicts.update(raw_dict)
    return merged_dicts