benedict.core.flatten._flatten_key()   A
last analyzed

Complexity

Conditions 3

Size

Total Lines 4
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 3
nop 3
1
from benedict.core import clone
2
from benedict.utils import type_util
3
4
5
def _flatten_key(base_key, key, separator):
6
    if base_key and separator:
7
        return f"{base_key}{separator}{key}"
8
    return key
9
10
11
def _flatten_item(d, base_dict, base_key, separator):
12
    new_dict = base_dict
13
    keys = list(d.keys())
14
    for key in keys:
15
        new_key = _flatten_key(base_key, key, separator)
16
        value = d.get(key, None)
17
        if type_util.is_dict(value):
18
            new_value = _flatten_item(
19
                value, base_dict=new_dict, base_key=new_key, separator=separator
20
            )
21
            new_dict.update(new_value)
22
            continue
23
        if new_key in new_dict:
24
            raise KeyError(f"Invalid key: '{new_key}', key already in flatten dict.")
25
        new_dict[new_key] = value
26
    return new_dict
27
28
29
def flatten(d, separator="_"):
30
    new_dict = clone(d, empty=True)
31
    return _flatten_item(d, base_dict=new_dict, base_key="", separator=separator)
32