Skip to content

Instantly share code, notes, and snippets.

@rndD
Last active August 29, 2015 14:06
Show Gist options
  • Save rndD/860859b460d969d749ce to your computer and use it in GitHub Desktop.
Save rndD/860859b460d969d749ce to your computer and use it in GitHub Desktop.
deep dict class
# -*- coding: utf-8 -*-
class deep_dict(dict):
def __init__(self, value=None):
if isinstance(value, dict):
for key in value:
self.__setitem__(
key,
deep_dict(value[key]) if isinstance(value[key], dict) else value[key]
)
else:
raise TypeError, 'expected dict'
def get(self, key, value=None):
d = super(deep_dict, self)
if '.' not in key:
return d.get(key, value)
my_key, rest = key.split('.', 1)
target = d.get(my_key, value)
return target.get(rest, value) if isinstance(target, deep_dict) else target
d = deep_dict({ 'foo': { 'bar': 'baz', 'foo': 1, 'b': { 'a': 2 } } })
print d.get('foo.bar')
print d.get('foo.foo')
print d.get('foo.foo2', 300)
print d.get('foo.b.a')
print d.get('foo.b.b')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment