Skip to content

Instantly share code, notes, and snippets.

@alanthai
Last active August 29, 2015 14:10
Show Gist options
  • Save alanthai/58265dc444d6ce858f3b to your computer and use it in GitHub Desktop.
Save alanthai/58265dc444d6ce858f3b to your computer and use it in GitHub Desktop.
Creates a nested dictionary with and without a specified depth level
# Unlimited depth nested dictionary
def nested_dict():
return defaultdict(nested_dict)
# Specify max depth of nested dictionary
def nested_dict(instance_type, max_depth):
def _nested_dict(depth):
if depth < max_depth:
return defaultdict(partial(_nested_dict, depth + 1))
return defaultdict(instance_type)
return _nested_dict(1)
# Example usage:
depth_level = 3
nested = nested_dict(int, depth_level)
nested['level1']['level2']['level3'] += 1 # Can use without instantiation
print nested['level1']['level2']['level3'] # returns 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment