flattree.logic module

flattree.logic.desparse(tree, na=None, reindex=True)

Converts branch(es) with integer keys into lists within a dictionary.

Dictionary with (all) integer keys acts as a sparse list with only non-void
values actually stored. This function would convert sparse list into the regular one.

Examples

{1: ‘one’, 3: ‘three’} -> [‘one’, ‘three’] # if reindex {1: ‘one’, 3: ‘three’} -> [na, ‘one’, na, ‘three’] # if not reindex

Parameters:
  • tree (dict) – dictionary
  • na – value to fill in gaps
  • reindex (bool) – if True, keep compact but change non-consecutive indices
Returns:

dict or list

flattree.logic.flatkey_to_keylist(flatkey, sep='.', esc='\\')

Converts flatkey to a list of key components, extracts list indices

Components that look like integers, e.g. ‘1000’ get converted to integers,
int(‘1000’) in this example.
Parameters:
  • flatkey (str) – flatkey string
  • sep (str) – symbol to use when joining flat key components
  • esc (str) – symbol to escape sep in key components
Returns:

key components, int if

Return type:

list

flattree.logic.genleaves(*trees, pre=None, sep='.', esc='\\', idxbase=0, list_merger=<function list_merger_list0>)

Generator used internally to merge trees and decompose them into leaves

Parameters:
  • trees – nested dictionaries to merge
  • pre – list of key components to prepend to resulting flatkey strings
  • sep (str) – symbol to use when joining flat key components
  • esc (str) – symbol to escape sep in key components
  • idxbase (int) – number at which list indices would start
  • list_merger – function called on trees when leading tree is a list
Yields:

tuples (flatkey, scalar leaf value) Example: (‘my.branch.x’, 0)

flattree.logic.keylist_to_flatkey(keylist, sep='.', esc='\\')

Converts list of key components to a flatkey string

Integer key components are considered list indices and get converted.

Parameters:
  • keylist (list) – list of key components
  • sep (str) – symbol to use when joining flat key components
  • esc (str) – symbol to escape sep in key components
Returns:

flatkey string

Return type:

str

flattree.logic.list_merger_list0(*lists)

Picks leading list, discards everything else

flattree.logic.unflatten(flatdata, root=None, sep='.', esc='\\', default=None, raise_key_error=False)

Restores nested dictionaries from a flat tree starting with a branch.

Parameters:
  • flatdata (dict) – dictionary of values indexed by flatkeys
  • root – branch to restore (None for the whole tree)
  • sep (str) – symbol to use when joining flat key components
  • esc (str) – symbol to escape sep in key components
  • default – default value Returned in case no branch is found and raise_key_error is False.
  • raise_key_error (bool) – if True, raise exception rather than return the default value in case no branch is found
Returns:

Tree or leaf value or default.