extended_data.primitives.mappings

This module provides utilities for handling maps (dictionaries).

It includes functions to manipulate, flatten, filter, and deeply merge dictionaries, and to convert keys from camelCase to snake_case.

Module Contents

Classes

SortedDefaultDict

A dictionary that combines :class:collections.defaultdict and :class:sortedcontainers.SortedDict functionality.

Functions

deep_merge

Deeply merge multiple mappings into a single dictionary.

create_merger

Create a custom Merger instance with specified strategies.

first_non_empty_value_from_map

Returns the first non-empty value from a map for the given keys.

deduplicate_map

Removes duplicate values from a map.

all_values_from_map

Returns all values from a nested map.

flatten_map

Flattens a nested dictionary into a flat dictionary.

zipmap

Creates a dictionary from two lists by zipping them together.

get_default_dict

Create a nested defaultdict with the specified number of levels.

unhump_map

Converts keys in a dictionary from camelCase to snake_case.

filter_map

Filters a map based on allowlist and denylist.

Data

API

extended_data.primitives.mappings._DEFAULT_MERGER = 'Merger(...)'
extended_data.primitives.mappings.deep_merge(*mappings: collections.abc.Mapping[str, Any]) dict[str, Any]

Deeply merge multiple mappings into a single dictionary.

This function recursively merges dictionaries, with later values taking precedence over earlier ones. Lists are appended, sets are unioned, and other types are overridden.

Args: *mappings: Variable number of mappings to merge. Later mappings take precedence over earlier ones.

Returns: A new dictionary containing the deeply merged result.

Example: >>> a = {“x”: {“y”: 1}, “list”: [1, 2]} >>> b = {“x”: {“z”: 2}, “list”: [3]} >>> deep_merge(a, b) {‘x’: {‘y’: 1, ‘z’: 2}, ‘list’: [1, 2, 3]}

extended_data.primitives.mappings.create_merger(list_strategy: str = 'append', dict_strategy: str = 'merge', set_strategy: str = 'union', fallback_strategy: str = 'override', type_conflict_strategy: str = 'override') deepmerge.merger.Merger

Create a custom Merger instance with specified strategies.

This factory function allows creating mergers with different behaviors for combining data structures.

Args: list_strategy: Strategy for merging lists. Options: “append”, “override”. dict_strategy: Strategy for merging dicts. Options: “merge”, “override”. set_strategy: Strategy for merging sets. Options: “union”, “override”. fallback_strategy: Default strategy for unhandled types. type_conflict_strategy: Strategy when types conflict.

Returns: A configured Merger instance.

Example: >>> merger = create_merger(list_strategy=”override”) >>> merger.merge({“a”: [1]}, {“a”: [2]}) {‘a’: [2]}

extended_data.primitives.mappings.first_non_empty_value_from_map(m: collections.abc.Mapping[str, Any], *keys: str) Any

Returns the first non-empty value from a map for the given keys.

Args: m (Mapping[str, Any]): The map to search. keys: The keys to search for.

Returns: Any: The first non-empty value.

extended_data.primitives.mappings.deduplicate_map(m: collections.abc.Mapping[str, Any]) dict[str, Any]

Removes duplicate values from a map.

Args: m (Mapping[str, Any]): The map to deduplicate.

Returns: dict[str, Any]: The deduplicated map.

extended_data.primitives.mappings.all_values_from_map(m: collections.abc.Mapping[str, Any]) list[Any]

Returns all values from a nested map.

Args: m (Mapping[str, Any]): The map to retrieve values from.

Returns: List[Any]: A list of all values.

extended_data.primitives.mappings.flatten_map(dictionary: collections.abc.Mapping[str, Any], parent_key: str | None = '', separator: str = '.') dict[str, Any]

Flattens a nested dictionary into a flat dictionary.

Args: dictionary (Mapping[str, Any]): The dictionary to flatten. parent_key (Optional[str]): The string to prepend to dictionary’s keys. separator (str): The string used to separate flattened keys.

Returns: Dict[str, Any]: The flattened dictionary.

extended_data.primitives.mappings.zipmap(a: list[str], b: list[str]) dict[str, str]

Creates a dictionary from two lists by zipping them together.

Args: a (List[str]): The first list. b (List[str]): The second list.

Returns: Dict[str, str]: The resulting dictionary.

extended_data.primitives.mappings.KT = 'TypeVar(...)'
extended_data.primitives.mappings.VT = 'TypeVar(...)'
class extended_data.primitives.mappings.SortedDefaultDict(default_factory: collections.abc.Callable[[], extended_data.primitives.mappings.VT] | None = None)

Bases: collections.defaultdict[extended_data.primitives.mappings.KT, extended_data.primitives.mappings.VT], sortedcontainers.SortedDict[extended_data.primitives.mappings.KT, extended_data.primitives.mappings.VT]

A dictionary that combines :class:collections.defaultdict and :class:sortedcontainers.SortedDict functionality.

This class inherits from both :class:collections.defaultdict and :class:sortedcontainers.SortedDict, providing a dictionary that both automatically creates values for missing keys and maintains its keys in sorted order.

The sorting behavior is inherited from :class:sortedcontainers.SortedDict, while the default value behavior comes from :class:collections.defaultdict. When keys are accessed that don’t exist, the default_factory is called to create a value, just like a regular :class:collections.defaultdict.

Args: default_factory (Callable[[], VT] | None): A callable that provides the default value for missing keys. If None, attempts to access missing keys will raise KeyError.

Example: >>> d = SortedDefaultDict(list) >>> d[‘c’].append(3) >>> d[‘a’].append(1) >>> d[‘b’].append(2) >>> list(d.keys()) [‘a’, ‘b’, ‘c’] >>> d[‘d’] # Creates new list automatically []

Initialization

Initialize a new SortedDefaultDict.

Args: default_factory: Callable that provides the default value for missing keys. When a key is accessed that doesn’t exist, this callable is invoked without arguments to provide the missing value. If None, accessing a missing key raises a KeyError.

Raises: TypeError: If default_factory is not callable or None.

extended_data.primitives.mappings.get_default_dict(use_sorted_dict: bool = False, default_type: type[dict[Any, Any]] = dict, levels: int = 2) collections.defaultdict[str, Any] | Any

Create a nested defaultdict with the specified number of levels.

Args: use_sorted_dict (bool): Whether to use a sorted dictionary. default_type (type): The default type for the dictionary. levels (int): The number of levels for nesting.

Returns: defaultdict | Any: A nested defaultdict or a dictionary of the specified type.

Raises: ValueError: If levels is less than 1.

extended_data.primitives.mappings.unhump_map(m: collections.abc.Mapping[str, Any], drop_without_prefix: str | None = None) dict[str, Any]

Converts keys in a dictionary from camelCase to snake_case.

Args: m (Mapping[str, Any]): The dictionary to convert. drop_without_prefix (Optional[str]): Drop keys without this prefix.

Returns: Dict[str, Any]: The converted dictionary.

extended_data.primitives.mappings.filter_map(m: collections.abc.Mapping[str, Any] | None, allowlist: list[str] | None = None, denylist: list[str] | None = None) tuple[dict[str, Any], dict[str, Any]]

Filters a map based on allowlist and denylist.

Args: m (Optional[Mapping[str, Any]]): The map to filter. allowlist (List[str]): The list of allowed keys. denylist (List[str]): The list of denied keys.

Returns: tuple[Dict[str, Any], Dict[str, Any]]: The filtered and remaining maps.