Skip to content

Instantly share code, notes, and snippets.

@laginha
Created August 6, 2013 16:01
Show Gist options
  • Save laginha/6165863 to your computer and use it in GitHub Desktop.
Save laginha/6165863 to your computer and use it in GitHub Desktop.
Get to a dictionary's value easily without explicitly checking the existence of previous keys in the dictionary tree.
class Dictionary(dict):
'''
d = Dictionary( {'foo': {'bar': 'foo'}} )
>>> d['foo']['bar']
'foo'
>>> d['foo']['foo']['bar']
{}
instead of:
if 'foo' in d:
if 'foo' in d['foo']:
d['foo']['foo'].get('bar')
'''
def __getitem__(self, key):
return self.get(key, Dictionary())
def __setitem__(self, key, val):
def handle_value(value):
if isinstance(value, dict):
return Dictionary( value )
if isinstance(value, list):
return [handle_value(i) for i in value]
return value
self.update( {key: handle_value( val )} )
def __init__(self, dic={}):
for key,val in dic.iteritems():
self[key] = val
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment