update dotdict to allow for get of a dotted string

This commit is contained in:
Jeff Bryner 2018-06-06 12:12:18 -07:00
Родитель b9485a135f
Коммит 8c5e1d0cd5
1 изменённых файлов: 24 добавлений и 0 удалений

Просмотреть файл

@ -17,3 +17,27 @@ class DotDict(dict):
if hasattr(value, 'keys'):
value = DotDict(value)
self[key] = value
def get(self, key):
"""get to allow for dot string notation
:param str key: Key in dot-notation (e.g. 'foo.lol').
:return: value. None if no value was found.
"""
try:
return self.__lookup(self, key)
except KeyError:
return None
def __lookup(self, dct, key):
"""Checks dct recursive to find the value for key.
Is used by get() interanlly.
:param dict dct: input dictionary
:param str key: The key we are looking for.
:return: The value.
:raise KeyError: If the given key is not found
"""
if '.' in key:
key, node = key.split('.', 1)
return self.__lookup(dct[key], node)
else:
return dct[key]