Skip to content

merge

Utility module for merging a list of dictionaries into a single dictionary.

This module provides a function to merge a list of dictionaries into a single dictionary. The function can handle nested dictionaries and lists.

Examples:

Basic usage with default merge strategy (append):

list_of_dicts = [
    {"a": 1, "b": 2},
    {"b": 3, "c": 4},
]
result = merge_dicts(list_of_dicts)
# Result: {'a': 1, 'b': 3, 'c': 4}

Using overwrite merge strategy:

list_of_dicts = [
    {"g": [7, 8]},
    {"g": [9, 10]},
]
result = merge_dicts(list_of_dicts, merge_strategy="overwrite")
# Result: {'g': [9, 10]}

Merging lists with dictionaries containing ‘key’:

list_of_dicts = [
    {"items": [{"key": "item1", "value": 1}]},
    {"items": [{"key": "item1", "value": 2}, {"key": "item2", "value": 3}]},
]
result = merge_dicts(list_of_dicts)
# Result: {'items': [{'key': 'item1', 'value': 2}, {'key': 'item2', 'value': 3}]}

Attributes

MergeStrategyType module-attribute

MergeStrategyType = Literal['append', 'overwrite']

T module-attribute

T = TypeVar('T', bound=BaseModel)

Functions

merge_dicts

merge_dicts(
    list_of_dicts: List[Dict[str, Any]],
    merge_strategy: MergeStrategyType = "append",
) -> Dict[str, Any]

Merge a list of dictionaries into a single dictionary.

Parameters:

  • list_of_dicts (List[Dict[str, Any]]) –

    A list of dictionaries to be merged.

  • merge_strategy (MergeStrategyType, default: 'append' ) –

    The merge strategy to use. ‘append’ will append new values to existing lists, ‘overwrite’ will overwrite existing values. Defaults to ‘append’.

Raises:

  • ValueError

    If an invalid merge_strategy is provided.

Returns:

  • Dict[str, Any]

    Dict[str, Any]: The merged dictionary.

model_override

model_override(
    orig: T,
    overrides: T | None,
    merge_strategy: MergeStrategyType = "append",
) -> T

Override the fields of an object that inherits from the Pydantic BaseModel with the fields of another model recursively.

Parameters:

  • orig (T) –

    The original model.

  • overrides (T | None) –

    The model with the fields to override in the original model.

  • merge_strategy (MergeStrategyType, default: 'append' ) –

    The merge strategy to use. ‘append’ will concatenate lists, ‘overwrite’ will replace the first list with the second. Defaults to ‘append’.

Returns:

  • T ( T ) –

    The new model with the fields overridden.