Created
August 6, 2013 16:01
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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