Last active
August 29, 2015 14:01
-
-
Save ekampf/b3bc844a16d60777fb1c to your computer and use it in GitHub Desktop.
Python Nested Dictionary
This file contains hidden or 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 Nil(object): | |
def __getitem__(self, key): | |
return Nil() | |
def __nonzero__(self): | |
return False | |
class NestedDict(dict): | |
def __init__(self, *args, **kwargs): | |
self.update(*args, **kwargs) | |
def __missing__(self, key): | |
return Nil() | |
def __setitem__(self, key, val): | |
if isinstance(val, dict): val = NestedDict(val) | |
dict.__setitem__(self, key, val) | |
def update(self, *args, **kwargs): | |
for k, v in dict(*args, **kwargs).iteritems(): | |
self[k] = v | |
x = NestedDict({ '1': { '2': { '3': {'4': { '5': 'eran' }}}} }) | |
if x['1']['2']['impossible!']: | |
print 'Its impossible we print here!' | |
else: | |
print 'all good' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment