diff --git a/benedict/dicts/keypath.py b/benedict/dicts/keypath.py index 9196f5d..903abbd 100644 --- a/benedict/dicts/keypath.py +++ b/benedict/dicts/keypath.py @@ -39,21 +39,7 @@ class KeypathDict(dict): dict_util.traverse(d, check_key) def _goto_keys(self, keys): - result = (None, None, None, ) - parent = self - i = 0 - j = len(keys) - while i < j: - key = keys[i] - try: - value = parent[key] - result = (parent, key, value, ) - parent = value - i += 1 - except (KeyError, TypeError, ): - result = (None, None, None, ) - break - return result + return dict_util.resolve(self, keys) def _list_keys(self, key): if isinstance(key, string_types): diff --git a/benedict/utils/dict_util.py b/benedict/utils/dict_util.py index 9968a8b..8675299 100644 --- a/benedict/utils/dict_util.py +++ b/benedict/utils/dict_util.py @@ -124,6 +124,31 @@ def remove(d, keys, *args): d.pop(key, None) +def resolve(d, keys, **kwargs): + create_intermediates = kwargs.pop('create_intermediates', False) + result = (None, None, None, ) + parent = d + i = 0 + j = len(keys) + while i < j: + key = keys[i] + try: + value = parent[key] + result = (parent, key, value, ) + parent = value + i += 1 + except (KeyError, ): + if create_intermediates: + parent[key] = {} + continue + result = (None, None, None, ) + break + except (TypeError, ValueError, ): + result = (None, None, None, ) + break + return result + + def standardize(d): def f(item, item_key, item_value): if isinstance(item_key, string_types):