Skip to content

Instantly share code, notes, and snippets.

@Slater-Victoroff
Created January 14, 2014 22:04
Show Gist options
  • Save Slater-Victoroff/8426757 to your computer and use it in GitHub Desktop.
Save Slater-Victoroff/8426757 to your computer and use it in GitHub Desktop.
I've gone too far this time
import collections
def rec_dict():
"""
Just a recursive dictionary
"""
return collections.defaultdict(rec_dict)
class Tree(object):
"""
A tree , automatically sets root nodes to zero [4][1] --> [4][1][0]
"""
def __init__(self, category_dict, depth=3):
self.tree = rec_dict()
nested_grab = lambda keys: reduce(lambda entry, key: entry.setdefault(key, {}), [self.tree] + keys)
for category, value in category_dict.items():
# The filter command means that something like 1.2. or 1..2 will go to 1.2, the added zeros are to set root behavior
actual_categories = (filter(None, category.split('.')) + ([0] * depth))
nested_grab(actual_categories[:depth-1])[actual_categories[depth-1]] = value
categories = {
'0' : 'Unclassified',
'1' : 'Media',
'1.1' : 'Literature',
'1.1.1': 'Book',
'1.1.2': 'Author',
'1.2' : 'Music'
}
test = Tree(categories)
print test.tree['1']['1']['1']
>>> 'Book'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment