3. Package reference
For greater convenience, the modules remain hidden inside the package. These modules are exposed for development purposes only.
3.1. Exceptions
This module provides specific exception classes for nested dictionaries. These exceptions extend the standard Exception, KeyError and AttributeError classes for future developments.
- exception ndict_tools.exception.StackedAttributeError
This exception is raised when a key is not compatible with stacked dictionary attributes.
- exception ndict_tools.exception.StackedDictionaryError(message: str | None = None, error: int = 0)
Exception raised when a stacked dictionary is invalid.
StackedDictionaryError exception class.
- Parameters:
message (str) – a message describing the error.
error (int) – an integer describing the error.
- Raises:
None
- exception ndict_tools.exception.StackedKeyError
Exception raised when a key is not compatible with a stacked dictionary.
- exception ndict_tools.exception.NestedDictionaryException(message: str | None = None, error: int = 0)
Raised when a nested dictionary is invalid.
StackedDictionaryError exception class.
- Parameters:
message (str) – a message describing the error.
error (int) – an integer describing the error.
- Raises:
None
3.2. Tools
This module provides an intermediate technical class and tools for manipulating nested dictionaries.
Although this module is hidden from the package’s external view, its contents are important. The _StackedDict
object
class orchestrates the basic attributes, functions and methods required to initialize and manage nested dictionaries.
This class could have been eliminated in favor of building all methods and tools into the main module containing the
NestedDictionary
object class. However, this choice will enable us to build stacks of different dictionaries in the
future, without necessarily using the properties specific to these dictionaries.
- ndict_tools.tools.unpack_items()
This function de-stacks items from a nested dictionary.
- Parameters:
dictionary (dict) – Dictionary to unpack.
- Returns:
Generator that yields items from a nested dictionary.
- Return type:
Generator
- ndict_tools.tools.from_dict()
This recursive function is used to transform a dictionary into a stacked dictionary.
This function enhances and replaces the previous from_dict() function in core module of this package. It allows you to create an object subclasses of a _StackedDict with initialization options if requested and attributes to be set.
- Parameters:
dictionary (dict) – dictionary to transform
class_name (object) – name of the class to return
class_options (dict) –
options to pass to the class or attributes of the class to be set
init : parameters to initialize instances of the class, this should be from
__init__
function of the classattributes : attributes to set the class attributes
- Returns:
stacked dictionary or of subclasses of _StackedDict
- Return type:
- Raises:
StackedKeyError – if attribute called is not an attribute of the hierarchy of classes
- class ndict_tools.tools._StackedDict(*args, **kwargs)
This class is an internal class for stacking nested dictionaries. This class is technical and is used to manage the processing of nested dictionaries. It inherits from defaultdict.
At instantiation, it has two mandatory parameters for its creation:
indent, which is used to format the object’s display.
default, which initializes the default_factory attribute of its parent class defaultdict.
These parameters are passed using the kwargs dictionary.
- Parameters:
args (iterator)
kwargs (dict)
- indent: int = 0
indent is used to print the dictionary with json indentation
- default_factory
Factory for default value called by __missing__().
- __str__()
Override __str__ to converts a nested dictionary to a string in json like format
- Parameters:
padding (int) – whitespace indentation of dictionary content
- Returns:
a string in json like format
- Return type:
str
- __copy__()
Override __copy__ to create a shallow copy of a stacked dictionary.
- Returns:
a shallow copy of a stacked dictionary
- Return type:
_StackedDict or a subclass of _StackedDict
- __deepcopy__()
Override __deepcopy__ to create a complete copy of a stacked dictionary.
- Returns:
a complete copy of a stacked dictionary
- Return type:
_StackedDict or a subclass of _StackedDict
- __setitem__()
Override __setitem__ to handle hierarchical keys.
- Parameters:
key (object) – key to set
value (object) – value to set
- Returns:
None
- Return type:
None
- Raises:
TypeError – if a nested list is found within the key
- __getitem__()
Override __getitem__ to handle hierarchical keys.
- Parameters:
key (object) – key to set
- Returns:
value
- Return type:
object
- Raises:
TypeError – if a nested list is found within the key
- __delitem__()
Override __delitem__ to handle hierarchical keys.
- Parameters:
key (object) – key to set
- Returns:
None
- Return type:
None
- unpacked_items()
This method de-stacks items from a nested dictionary. It calls internal unpack_items() function.
- Returns:
generator that yields items from a nested dictionary
- Return type:
Generator
- unpacked_keys()
This method de-stacks keys from a nested dictionary and return them as keys. It calls internal unpack_items() function.
- Returns:
generator that yields keys from a nested dictionary
- Return type:
Generator
- unpacked_values()
This method de-stacks values from a nested dictionary and return them as values. It calls internal unpack_items() function.
- Returns:
generator that yields values from a nested dictionary
- Return type:
Generator
- pop()
Removes the specified key (or hierarchical key) and returns its value. If the key does not exist, returns the default value if provided, or raises a KeyError.
- Parameters:
key (Union[Any, List[Any]]) – The key or hierarchical key to remove.
default (Any) – The value to return if the key does not exist.
- Returns:
The value associated with the removed key.
- Return type:
Any
- Raises:
StackedKeyError – If the key does not exist and no default is provided.
- popitem()
Removes and returns the last item in the most deeply nested dictionary as a (path, value) pair. The path is represented as a list of keys leading to the value. If the dictionary is empty, raises a KeyError.
The method follows a depth-first search (DFS) traversal to locate the last item, removing it from the nested structure before returning.
- Returns:
A tuple containing the hierarchical path (list of keys) and the value.
- Return type:
tuple
- Raises:
IndexError – If the dictionary is empty.
- to_dict()
This method converts a nested dictionary to a classical dictionary
- Returns:
a dictionary
- Return type:
dict
- update()
Updates a stacked dictionary with key/value pairs from a dictionary or keyword arguments.
- Parameters:
dictionary (dict) – A dictionary with key/value pairs to update.
kwargs (dict) – Additional key/value pairs to update.
- Returns:
None
- occurrences()
Returns the Number of occurrences of a key in a stacked dictionary including 0 if the key is not a keys in a stacked dictionary.
- Parameters:
key (Any) – A possible key in a stacked dictionary.
- Returns:
Number of occurrences or 0
- Return type:
int
- is_key()
Checks if a key exists at any level in the _StackedDict hierarchy using unpack_items(). This works for both flat keys (e.g., 1) and hierarchical keys (e.g., [1, 2, 3]).
- Parameters:
key – A key to check. Can be a single key or a part of a hierarchical path.
- Returns:
True if the key exists at any level, False otherwise.
- key_list()
returns the list of unpacked keys containing the key from the stacked dictionary. If the key is not in the dictionary, it raises StackedKeyError (not a key).
- Parameters:
key (Any) – a possible key in a stacked dictionary.
- Returns:
A list of unpacked keys containing the key from the stacked dictionary.
- Return type:
list
- Raises:
StackedKeyError – if a key is not in a stacked dictionary.
- items_list()
returns the list of unpacked items associated to the key from the stacked dictionary. If the key is not in the dictionary, it raises StackedKeyError (not a key).
- Parameters:
key (Any) – a possible key in a stacked dictionary.
- Returns:
A list of unpacked items associated the key from the stacked dictionary.
- Return type:
list
- Raises:
StackedKeyError – if a key is not in a stacked dictionary.
- to_dict()
This method converts a nested dictionary to a classical dictionary
- Returns:
a dictionary
- Return type:
dict
- height()
Computes the height of the _StackedDict, defined as the length of the longest path.
- Returns:
The height of the dictionary.
- Return type:
int
- size()
Computes the size of the _StackedDict, defined as the total number of keys (nodes) in the structure.
- Returns:
The total number of nodes in the dictionary.
- Return type:
int
- leaves()
Extracts the leaf nodes of the _StackedDict.
- Returns:
A list of leaf values.
- Return type:
list
- is_balanced()
Checks if the _StackedDict is balanced. A balanced dictionary is one where the height difference between any two subtrees is at most 1.
- Returns:
True if balanced, False otherwise.
- Return type:
bool
- ancestors()
Finds the ancestors (keys) of a given value in the nested dictionary.
- Parameters:
value (Any) – The value to search for in the nested dictionary.
- Returns:
A list of keys representing the path to the value.
- Return type:
List[Any]
- Raises:
ValueError – If the value is not found in the dictionary.
3.3. Core
This module provides tools and class for creating nested dictionaries, since standard python does not have nested dictionaries.
- class ndict_tools.core.NestedDictionary(*args, **kwargs)
Nested dictionary class.
This class is designed as a stacked dictionary. It represents a nest of dictionaries, that is to say that each key is a value or a nested dictionary. And so on…
This function initializes a nested dictionary.
- Parameters:
args (Iterable) – the first one of the list must be a dictionary to instantiate an object.
kwargs (dict) –
enrichments settings and
indent : indentation of the printable nested dictionary (used by json.dumps() function)
strict : strict mode (False by default) define default answer to unknown key
Example
NestedDictionary({'first': 1,'second': {'1': "2:1", '2': "2:2", '3': "3:2"}, 'third': 3, 'fourth': 4})
NestedDictionary(zip(['first','second', 'third', 'fourth'], [1, {'1': "2:1", '2': "2:2", '3': "3:2"}, 3, 4]))
NestedDictionary([('first', 1), ('second', {'1': "2:1", '2': "2:2", '3': "3:2"}), ('third', 3), ('fourth', 4)])
- __str__()
Override __str__ to converts a nested dictionary to a string in json like format
- Parameters:
padding (int) – whitespace indentation of dictionary content
- Returns:
a string in json like format
- Return type:
str