Skip to content

Commit

Permalink
tests: Handle list element in {get,set}_dict_element function
Browse files Browse the repository at this point in the history
Add ability to give int in the path so that we can take an element of
the list `mydict.0` to get the first element of the list in `mydict`
  • Loading branch information
TeddyAndrieux committed May 27, 2020
1 parent 12028b4 commit ff9066c
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions tests/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,11 @@ def get_dict_element(data, path, delimiter='.'):
Traverse a dict using a 'delimiter' on a target string.
getitem(a, b) returns the value of a at index b
"""
return functools.reduce(operator.getitem, path.split(delimiter), data)
return functools.reduce(
operator.getitem,
(int(k) if k.isdigit() else k for k in path.split(delimiter)),
data
)


def set_dict_element(data, path, value, delimiter='.'):
Expand All @@ -179,9 +183,12 @@ def set_dict_element(data, path, value, delimiter='.'):
and replace the value of a key
"""
current = data
elements = path.split(delimiter)
elements = [int(k) if k.isdigit() else k for k in path.split(delimiter)]
for element in elements[:-1]:
current = current.setdefault(element, {})
if isinstance(element, int):
current = current[element] if len(current) > element else []
else:
current = current.setdefault(element, {})
current[elements[-1]] = value


Expand Down

0 comments on commit ff9066c

Please sign in to comment.