benedict.core.nest.nest()   A
last analyzed

Complexity

Conditions 3

Size

Total Lines 10
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 10
rs 9.95
c 0
b 0
f 0
cc 3
nop 4
1
from benedict.core.groupby import groupby
2
3
4
def _nest_items(nested_items, item, id_key, children_key):
5
    children_items = nested_items.pop(item[id_key], [])
6
    item[children_key] = children_items
7
    for child_item in children_items:
8
        _nest_items(nested_items, child_item, id_key, children_key)
9
10
11
def nest(items, id_key, parent_id_key, children_key):
12
    if any(
13
        [id_key == parent_id_key, id_key == children_key, parent_id_key == children_key]
14
    ):
15
        raise ValueError("keys should be different.")
16
    nested_items = groupby(items, parent_id_key)
17
    root_items = nested_items.get(None, [])
18
    for item in root_items:
19
        _nest_items(nested_items, item, id_key, children_key)
20
    return nested_items.get(None)
21