Skip to content

Commit d5c3189

Browse files
committed
Add get nested trait
1 parent 33d3622 commit d5c3189

3 files changed

Lines changed: 32 additions & 3 deletions

File tree

pathtraits/access.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,32 @@
1111
logger = logging.getLogger(__name__)
1212

1313

14+
def nest_dict(flat_dict, delimiter="/"):
15+
"""
16+
Transforms a flat dictionary with path-like keys into a nested dictionary.
17+
18+
:param flat_dict: The flat dictionary with path-like keys.
19+
:param delimiter: The delimiter used in the keys (default is '/').
20+
:return: A nested dictionary.
21+
"""
22+
nested_dict = {}
23+
24+
for path, value in flat_dict.items():
25+
keys = path.split(delimiter)
26+
current = nested_dict
27+
28+
for key in keys[:-1]:
29+
# If the key doesn't exist or is not a dictionary, create/overwrite it as a dictionary
30+
if key not in current or not isinstance(current[key], dict):
31+
current[key] = {}
32+
current = current[key]
33+
34+
# Set the value at the final key
35+
current[keys[-1]] = value
36+
37+
return nested_dict
38+
39+
1440
def get_dict(self, path):
1541
"""
1642
Get traits for a path as a Python dictionary
@@ -40,6 +66,7 @@ def get_dict(self, path):
4066
if not (v and k != "path"):
4167
continue
4268
res[k] = v
69+
res = nest_dict(res)
4370
return res
4471

4572

pathtraits/db.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,10 +54,11 @@ def merge_rows(rows: list):
5454
for row in rows:
5555
for k, v in row.items():
5656
# pylint: disable=C0201
57-
if k in res.keys() and v not in res[k]:
57+
if not k in res.keys():
58+
res[k] = []
59+
if not v in res[k]:
5860
res[k].append(v)
59-
else:
60-
res[k] = [v]
61+
6162
# simplify lists with just one element
6263
# ensure fixed order of list entries
6364
res = {k: sorted(v, key=str) if len(v) > 1 else v[0] for k, v in res.items()}

test/test.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ def test_eu(self):
4747
"is_example": True,
4848
"score": 3.5,
4949
"users": ["dloos", "fgans"],
50+
"foo": {"bar": {"a": 1, "b": 2, "c": [1, 2, 3]}},
5051
}
5152
for k, v in target.items():
5253
self.assertEqual(source[k], v)

0 commit comments

Comments
 (0)