Passed
Push — master ( 969640...b3caf6 )
by Fabio
01:22
created

benedict.core.flatten._flatten_key()   A

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
# -*- coding: utf-8 -*-
2
3
from benedict.utils import type_util
4
5
6
def _flatten_key(base_key, key, separator):
7
    if base_key and separator:
8
        return '{}{}{}'.format(base_key, separator, key)
9
    return key
10
11
12
def flatten(d, separator='_', **kwargs):
13
    new_dict = d.copy()
14
    new_dict.clear()
15
    keys = list(d.keys())
16
    base_key = kwargs.pop('base_key', '')
17
    for key in keys:
18
        value = d.get(key, None)
19
        new_key = _flatten_key(base_key, key, separator)
20
        if type_util.is_dict(value):
21
            new_value = flatten(value, separator=separator, base_key=new_key)
22
            new_value.update(new_dict)
23
            new_dict.update(new_value)
24
            continue
25
        new_dict[new_key] = value
26
    return new_dict
27