Skip to content

Instantly share code, notes, and snippets.

@ekampf
Last active August 29, 2015 14:01
Show Gist options
  • Save ekampf/b3bc844a16d60777fb1c to your computer and use it in GitHub Desktop.
Save ekampf/b3bc844a16d60777fb1c to your computer and use it in GitHub Desktop.
Python Nested Dictionary
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