Skip to content

Instantly share code, notes, and snippets.

@wchan2
Last active August 29, 2015 14:26
Show Gist options
  • Save wchan2/f9f2665489ceba3d3790 to your computer and use it in GitHub Desktop.
Save wchan2/f9f2665489ceba3d3790 to your computer and use it in GitHub Desktop.
Dictionary Tree

Dictionary Tree

Given a tuple, it creates a tree with nested dictionaries and then finally the respective counts for the sequence for the number of times it appears.

Sample Run

dct = {} 
incr_dict(dct, ('a', 'b', 'c')) 
dct # {'a': {'b': {'c': 1}}} 

incr_dict(dct, ('a', 'b', 'c')) 
dct # {'a': {'b': {'c': 2}}} 

incr_dict(dct, ('a', 'b', 'f')) 
dct # {'a': {'b': {'c': 2, 'f': 1}}} 

incr_dict(dct, ('a', 'r', 'f')) 
dct # {'a': {'r': {'f': 1}, 'b': {'c': 2, 'f': 1}}} 

incr_dict(dct, ('a', 'z')) 
dct # {'a': {'r': {'f': 1}, 'b': {'c': 2,'f': 1}, 'z': 1}} 
def incr_dict(dictionary, elements):
if len(elements) == 0:
return
updated = dictionary
for element in elements[:-1]:
if element not in updated:
updated[element] = {}
updated = updated[element]
if elements[-1] not in updated:
updated[elements[-1]] = 1
else:
updated[elements[-1]] += 1
import unittest
from dict_tree import incr_dict
class TestIncrDict(unittest.TestCase):
def setUp(self):
self.dict = {}
incr_dict(self.dict, ('a', 'b', 'c'))
def tearDown(self):
self.dict = None
def test_empty_sequence(self):
dct = {}
incr_dict(dct, ())
self.assertEqual(dct, {})
def test_adding_initial_sequence(self):
self.assertEqual(self.dict, {'a': {'b': {'c': 1}}})
def test_adding_the_same_sequence(self):
incr_dict(self.dict, ('a', 'b', 'c'))
self.assertEqual(self.dict, {'a': {'b': {'c': 2}}})
def test_adding_a_sequence_that_with_different_leaf_node(self):
incr_dict(self.dict, ('a', 'b', 'f'))
self.assertEqual(self.dict, {'a': {'b': {'c': 1, 'f': 1}}})
def test_adding_a_sequence_that_with_different_middle_node(self):
incr_dict(self.dict, ('a', 'r', 'c'))
self.assertEqual(self.dict, {'a': {'b': {'c': 1}, 'r': {'c': 1}}})
def test_adding_shorter_sequence(self):
incr_dict(self.dict, ('a', 'z'))
self.assertEqual(self.dict, {'a': {'b': {'c': 1}, 'z': 1}})
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment