libb.add_branch

add_branch(tree, vector, value)[source]

Insert a value into a dict at the path specified by vector.

Given a dict, a vector, and a value, insert the value into the dict at the tree leaf specified by the vector. Recursive!

Parameters:
  • tree (dict) – The data structure to insert the vector into.

  • vector (list) – A list of values representing the path to the leaf node.

  • value – The object to be inserted at the leaf.

Returns:

The dict with the value placed at the path specified.

Return type:

dict

Algorithm:
  • If we’re at the leaf, add it as key/value to the tree

  • Else: If the subtree doesn’t exist, create it.

  • Recurse with the subtree and the left shifted vector.

  • Return the tree.

Useful for parsing ini files with dot-delimited keys:

[app]
site1.ftp.host = hostname
site1.ftp.username = username
site1.database.hostname = db_host

Example 1:

>>> tree = {'a': 'apple'}
>>> vector = ['b', 'c', 'd']
>>> value = 'dog'
>>> tree = add_branch(tree, vector, value)
>>> unnest(tree)
[('a', 'apple'), ('b', 'c', 'd', 'dog')]

Example 2:

>>> vector2 = ['b', 'c', 'e']
>>> value2 = 'egg'
>>> tree = add_branch(tree, vector2, value2)
>>> unnest(tree)
[('a', 'apple'), ('b', 'c', 'd', 'dog'), ('b', 'c', 'e', 'egg')]