Skip to content

dataherb.utils.data

utils.data¤

flatten_dict(nested_dict, sep=None) ¤

flatten_dict flattens a dictionary,

The flattened keys are joined using a separater which is default to '__'.

Parameters:

Name Type Description Default
nested_dict dict

input nested dictionary to be flattened.

required
sep str, optional

seperator for the joined keys, defaults to __

None

Returns:

Type Description
dict

flattened dictionar

Source code in dataherb/utils/data.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
def flatten_dict(nested_dict, sep=None):
    """
    flatten_dict flattens a dictionary,

    The flattened keys are joined using a separater which is default to '__'.

    :param nested_dict: input nested dictionary to be flattened.
    :type nested_dict: dict
    :param sep: seperator for the joined keys, defaults to __
    :type sep: str, optional
    :return: flattened dictionar
    :rtype: dict
    """
    if sep is None:
        sep = "__"
    res = {}

    def flatten(x, name=""):
        if type(x) is dict:
            for a in x:
                flatten(x[a], name + a + sep)
        elif type(x) is list:
            i = 0
            for a in x:
                flatten(a, name + str(i) + sep)
                i += 1
        else:
            res[name[:-2]] = x

    flatten(nested_dict)

    return res