Last active
August 29, 2015 14:10
-
-
Save alanthai/58265dc444d6ce858f3b to your computer and use it in GitHub Desktop.
Creates a nested dictionary with and without a specified depth level
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
# 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