Skip to content

utils

MODULE DESCRIPTION
logging

merge_dicts_with_priority

merge_dicts_with_priority(
    dict1: dict, dict2: dict | None
) -> dict

Merges two dictionaries with priority to dict1.

All keys and values from dict1 will be returned in the new dictionary, substituting keys with different values from dict2. Keys and values exclusive to dict2 will be returned as well. The function is recursively called for all nested dictionaries.

PARAMETER DESCRIPTION

dict1

Priority dictionary to merge. Values in dict1 are always in the returned dictionary.

TYPE: dict

dict2

Secondary dictionary to merge.

TYPE: dict

RETURNS DESCRIPTION
dict

Merged dictionary.

TYPE: dict

Source code in src/downmixer/utils/__init__.py
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
def merge_dicts_with_priority(dict1: dict, dict2: dict | None) -> dict:
    """Merges two dictionaries with priority to `dict1`.

    All keys and values from `dict1` will be returned in the new dictionary, substituting keys with different
    values from `dict2`. Keys and values exclusive to `dict2` will be returned as well. The function is
    recursively called for all nested dictionaries.

    Args:
        dict1 (dict): Priority dictionary to merge. Values in dict1 are always in the returned dictionary.
        dict2 (dict): Secondary dictionary to merge.

    Returns:
        dict: Merged dictionary.
    """
    new_dict = dict1.copy()

    if dict2 is not None:
        for key, value in dict2.items():
            if (
                key in new_dict
                and isinstance(new_dict[key], dict)
                and isinstance(value, dict)
            ):
                new_dict[key] = merge_dicts_with_priority(new_dict[key], value)
            elif key not in new_dict:
                new_dict[key] = value

    return new_dict

safe_get

safe_get(dict, *args, default=None)
Source code in src/downmixer/utils/__init__.py
34
35
36
37
38
39
40
41
42
43
44
45
46
47
def safe_get(dict, *args, default=None):
    for arg in args:
        try:
            value = dict.get(arg)
            next_args = args[1:]

            if len(next_args) != 0:
                return safe_get(value, *next_args)
            else:
                return value
        except AttributeError:
            continue

    return default