Skip to content

Commit f8cdc4c

Browse files
Merge pull request #12 from Agent-Hellboy/issue-10
Fix #10
2 parents 5dd64d6 + fd186f7 commit f8cdc4c

File tree

2 files changed

+16
-8
lines changed

2 files changed

+16
-8
lines changed

src/trace_dkey/__init__.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,20 +27,23 @@ def __trace_key(dict_key: Any, dict_value: Any, key: Any, path: List[Union[str,
2727
if dict_key_value == key:
2828
paths = [path]
2929
else:
30-
# branch to iterate over list of keys
30+
# branch to iterate over list of keys
31+
# this branch will iterate over keys like {'a':1,'b':2,'c':3}
3132
if (type(dict_value) == _ast.Dict and len(dict_value.keys) > 0):
3233
for i in range(len(dict_value.keys)):
3334
# find array of paths inside the ith branch
3435
branch_paths = __trace_key(dict_value.keys[i], dict_value.values[i], key, path)
3536
paths = [*paths, *branch_paths]
3637

37-
# branch to iterate over dict of list
38+
# branch to iterate over dict of list
39+
# this branch will iterate over keys like {'a':1,'b':2,'c':[{'d':'e']}} but skip if c value is list of other types ['d','e']
3840
if (type(dict_value) == _ast.List):
3941
for elt in dict_value.elts:
40-
for i in range(len(elt.keys)):
41-
# find array of paths inside the ith branch
42-
branch_paths = __trace_key(elt.keys[i], elt.values[i], key, path)
43-
paths = [*paths, *branch_paths]
42+
if type(elt) == _ast.Dict:
43+
for i in range(len(elt.keys)):
44+
# find array of paths inside the ith branch
45+
branch_paths = __trace_key(elt.keys[i], elt.values[i], key, path)
46+
paths = [*paths, *branch_paths]
4447
return paths
4548

4649

tests/test_trace_dkey.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,9 @@ def test_trace_fixture():
1919
fixture4 = trace(dict4, 'c')
2020
dict5={'a':'b','c':{'d':[{'e':'f'}]}}
2121
fixture5 = trace(dict5,'e')
22-
return fixture1, fixture2, fixture3, fixture4, fixture5
22+
dict6={'a':'b','c':{'d':['e','f']}}
23+
fixture6 = trace(dict6,'e')
24+
return fixture1, fixture2, fixture3, fixture4, fixture5, fixture6
2325

2426

2527
def test_when_key_is_string(test_trace_fixture):
@@ -35,4 +37,7 @@ def test_when_multiple_keys_found(test_trace_fixture):
3537
assert test_trace_fixture[3] == [['a', 'b', 'c'], ['a', 'c']]
3638

3739
def test_when_keys_found_in_list(test_trace_fixture):
38-
assert test_trace_fixture[4] == [['c', 'd','e']]
40+
assert test_trace_fixture[4] == [['c', 'd','e']]
41+
42+
def test_when_keys_not_found_in_list(test_trace_fixture):
43+
assert test_trace_fixture[5] == []

0 commit comments

Comments
 (0)