NestifyDict package

Submodules

NestifyDict

Module contents

A tool for parsing structured data (primarily nested dictionaries from json files). In particular it can flatten dictionaries, map flattened dicts to a template, and recursively get/set elements in nested dictionaries without a priori knowledge of the structure.

nestifydict.find_key(d: dict, key)

Finds first instance of key in nested dict

Parameters:
  • d – (dict) dictionary to search

  • key – () key

Returns:

(list) Returns order of keys to access element or None if nonexistent

nestifydict.merge(d_default: dict, d_merge: dict, do_append: bool = False)

Adds d_merge values to d_default recursively. Values in d_merge overwrite those of d_default values, however nonexistent values in d_default are retained, which differs from use of {**d_base, **d_merge}

Parameters:
  • d_default – (dict) base dictionary

  • d_merge – (dict) dictionary to add

  • do_append – (bool) if true, will append iterable elements of not dict type, default: Flase

Returns:

(dict) combined dictionary

nestifydict.merge_all(configs: list, do_append: bool = False)

Accepts a list of configurations and merges them into a single one

Parameters:
  • configs – (list(dict)) Configs to merge, if priority matters, later defaults in each group will overwrite earlier ones.

  • do_append – (bool) if true, will append iterable elements of not dict type, default: Flase

Returns:

merged configuration

nestifydict.recursive_get(d: dict, key: list)

Returns value from dict recursive key

Parameters:
  • d – (dict) dictionary containing key

  • key – (list) list of keys

Returns:

() Value

nestifydict.recursive_set(d: dict, key: list, val, as_hint=False)

Updates dictionary value given an ordered list of keys. Can also support keys as hints and will search for the first key before attempting to set it. (Later may update find_key to match a list of keys or make a find_key_list function) In either case, if key is not found it will be added to root.

Parameters:
  • d – (dict) dictionary to update

  • key – (list) list of keys

  • val – () value

  • as_hint – (bool) if true, attempts to find key before setting it, default: False

nestifydict.structure(d_flat: dict, d_structure: dict, reject_nonexistent: bool = True)

Maps dictionary to a preferred structure

This will consume d_flat

Parameters:
  • d_flat – (dict) dict containing values

  • d_structure – (dict) dictionary containing structure and default values

  • reject_nonexistent – (bool) If true, keys of d_flat not in d_structure will be thrown out, default: True

Returns:

Structured dictionary

nestifydict.unstructure(d)

Flattens nested dictionary (if keys are used multiple places, they will be overwritten)

Parameters:

d – (dict) dictionary to flatten

Returns:

(dict) keys and values for each element in d