Passed
Push — master ( b49b7e...60d050 )
by Fabio
59s
created

benedict.core.flatten._flatten_item()   A

Complexity

Conditions 4

Size

Total Lines 19
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

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