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

benedict.core.flatten   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 27
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 6
eloc 21
dl 0
loc 27
rs 10
c 0
b 0
f 0

2 Functions

Rating   Name   Duplication   Size   Complexity  
A flatten() 0 15 3
A _flatten_key() 0 4 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