Passed
Push — master ( df1182...461010 )
by Fabio
01:14
created

benedict.utils.utility_util.flatten()   A

Complexity

Conditions 4

Size

Total Lines 11
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
cc 4
nop 3
1
# -*- coding: utf-8 -*-
2
3
from six import string_types
4
5
import copy
6
import json
7
8
9
def clean(d, strings=True, dicts=True, lists=True):
10
    keys = list(d.keys())
11
    for key in keys:
12
        value = d.get(key, None)
13
        if not value:
14
            if value is None or \
15
                    strings and isinstance(value, string_types) or \
16
                    dicts and isinstance(value, dict) or \
17
                    lists and isinstance(value, (list, tuple, )):
18
                del d[key]
19
20
21
def clone(d):
22
    return copy.deepcopy(d)
23
24
25
def dump(data):
26
    def encoder(obj):
27
        json_types = (bool, dict, float, int, list, tuple, ) + string_types
28
        if not isinstance(obj, json_types):
29
            return str(obj)
30
    return json.dumps(data, indent=4, sort_keys=True, default=encoder)
31
32
33
def flatten(d, separator='_', base=''):
34
    f = {}
35
    keys = sorted(d.keys())
36
    for key in keys:
37
        value = d.get(key)
38
        keypath = '{}{}{}'.format(base, separator, key) if base and separator else key
39
        if isinstance(value, dict):
40
            f.update(flatten(value, separator, keypath))
41
        else:
42
            f[keypath] = value
43
    return f
44
45
46
def filter(d, predicate):
47
    f = {}
48
    keys = d.keys()
49
    for key in keys:
50
        value = d.get(key, None)
51
        if predicate(key, value):
52
            f[key] = value
53
    return f
54
55
56
def merge(d, other):
57
    for key, value in other.copy().items():
58
        src = d.get(key, None)
59
        if isinstance(src, dict) and isinstance(value, dict):
60
            merge(src, value)
61
        else:
62
            d[key] = value
63
    return d
64