Skip to content

Instantly share code, notes, and snippets.

@richmondwang
Created March 31, 2017 07:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richmondwang/e18fb2942f9e16bb6d8f24964e81524b to your computer and use it in GitHub Desktop.
Save richmondwang/e18fb2942f9e16bb6d8f24964e81524b to your computer and use it in GitHub Desktop.
This subclass is used for dicts with guaranteed values of children but can still be used like a normal dict.
class SureDict(dict):
"""
This subclass is used for dicts with guaranteed values of children but
can still be used like a normal dict.
.. note::
Note that only the top level will be of class SureDict, those children
whose values are of dict will remain dict.
Example::
>>> a_dict = {
... 'aKey': 'a value',
... 'top': {
... 'child1': 'child2 is a dict',
... 'child2': {
... 'grandSon': 'this is a boy',
... 'grandDaughter': 'this is a girl'
... }
... }
... }
>>> a_dict.get('top:child1')
>>> a_dict.get('top:child1', 'Nothing')
'Nothing'
>>> sure_dict = SureDict(a_dict)
>>> sure_dict.get('top:child1')
'child2 is a dict'
>>> sure_dict.get('top:child2:grandSon')
'this is a boy'
>>> sure_dict.get('top:child2:grandDaughter')
'this is a girl'
>>> sure_dict.get('top:child2:grandMother')
>>> sure_dict.get('top:child2:grandMother', 'Nothing')
'Nothing'
>>> child_dict = sure_dict.get('top')
>>> child_dict.get('child2')
{'grandSon': 'this is a boy', 'grandDaughter': 'this is a girl'}
>>> child_dict.get('child2:grandSon')
>>> child_dict.get('child2:grandSon', 'Nothing')
'Nothing'
"""
def get(self, k, d=None):
assert type(k) is str, "Keys must be strings."
keys = k.split(":")
_last_key = keys.pop(0)
value = super().get(_last_key, d)
for key in keys:
assert isinstance(value,
dict), "Expected dict for child of '%s' key but" \
" got the value '%s' instead." % (
_last_key, value)
value = value.get(key, d)
return value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment