🔍 Code Extractor

function merge_option_dicts

Maturity: 51

Performs a deep merge of two nested dictionaries where the top-level values are themselves dictionaries, preserving values from both dictionaries at the nested level.

File:
/tf/active/vicechatdev/patches/util.py
Lines:
220 - 242
Complexity:
simple

Purpose

This function is designed to merge option dictionaries in a hierarchical structure, where each top-level key represents an option type containing its own dictionary of options. Unlike a shallow update that would replace entire nested dictionaries, this function merges the nested dictionaries individually, preserving options from old_opts that aren't overridden by new_opts. This is particularly useful for configuration management where you want to update specific options without losing other options of the same type.

Source Code

def merge_option_dicts(old_opts, new_opts):
    """
    Update the old_opts option dictionary with the options defined in
    new_opts. Instead of a shallow update as would be performed by calling
    old_opts.update(new_opts), this updates the dictionaries of all option
    types separately.

    Given two dictionaries
        old_opts = {'a': {'x': 'old', 'y': 'old'}}
    and
        new_opts = {'a': {'y': 'new', 'z': 'new'}, 'b': {'k': 'new'}}
    this returns a dictionary
        {'a': {'x': 'old', 'y': 'new', 'z': 'new'}, 'b': {'k': 'new'}}
    """
    merged = dict(old_opts)

    for option_type, options in new_opts.items():
        if option_type not in merged:
            merged[option_type] = {}

        merged[option_type].update(options)

    return merged

Parameters

Name Type Default Kind
old_opts - - positional_or_keyword
new_opts - - positional_or_keyword

Parameter Details

old_opts: A dictionary with a two-level nested structure where top-level keys represent option types and their values are dictionaries containing the actual options. This represents the base or default configuration that will be updated. Expected format: {'option_type': {'option_key': 'option_value'}}

new_opts: A dictionary with the same two-level nested structure as old_opts, containing new or updated options. Options in this dictionary will override corresponding options in old_opts, but won't remove options that only exist in old_opts. Expected format: {'option_type': {'option_key': 'option_value'}}

Return Value

Returns a new dictionary with the same two-level nested structure as the input dictionaries. The returned dictionary contains all option types from both old_opts and new_opts. For each option type, the nested dictionary contains all options from old_opts merged with options from new_opts, where new_opts values take precedence in case of key conflicts. Type: dict[str, dict[str, Any]]

Usage Example

# Basic usage example
old_opts = {
    'plot': {'width': 800, 'height': 600, 'title': 'Old Title'},
    'style': {'color': 'blue', 'alpha': 0.5}
}

new_opts = {
    'plot': {'height': 400, 'title': 'New Title', 'toolbar': True},
    'backend': {'renderer': 'bokeh'}
}

merged = merge_option_dicts(old_opts, new_opts)
# Result:
# {
#     'plot': {'width': 800, 'height': 400, 'title': 'New Title', 'toolbar': True},
#     'style': {'color': 'blue', 'alpha': 0.5},
#     'backend': {'renderer': 'bokeh'}
# }

print(merged['plot']['width'])  # 800 (preserved from old_opts)
print(merged['plot']['height'])  # 400 (updated from new_opts)
print(merged['style'])  # {'color': 'blue', 'alpha': 0.5} (entirely from old_opts)

Best Practices

  • This function assumes a two-level nested dictionary structure. It will not work correctly for deeper nesting levels.
  • The function creates a shallow copy of old_opts at the top level but performs updates on nested dictionaries, so nested dictionaries in the result may share references with the input dictionaries.
  • If new_opts contains non-dictionary values at the top level, calling .update() on them will raise an AttributeError.
  • The function does not modify the input dictionaries; it returns a new merged dictionary.
  • For option types that exist only in new_opts, they are added to the result with all their nested options.
  • This is particularly useful for configuration systems where options are grouped by type or category.

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function merge_options_to_dict 76.2% similar

    Merges a collection of Option objects or partial option dictionaries into a single unified dictionary by iterating through the collection and combining their key-value pairs.

    From: /tf/active/vicechatdev/patches/util.py
  • function merge_dimensions 48.0% similar

    Merges multiple lists of Dimension objects by combining their values while preserving unique dimensions and maintaining order of first appearance.

    From: /tf/active/vicechatdev/patches/util.py
  • function group_select 47.7% similar

    Recursively groups a list of key tuples into a nested dictionary structure to optimize indexing operations by avoiding duplicate key lookups.

    From: /tf/active/vicechatdev/patches/util.py
  • function resolve_dependent_kwargs 42.9% similar

    Resolves parameter dependencies in a dictionary by evaluating dependent parameter values, Parameterized instance methods, and parameterized functions.

    From: /tf/active/vicechatdev/patches/util.py
  • function compare_document_versions 37.8% similar

    Compares two document versions by their UIDs and generates a summary of changes including metadata differences and hash comparisons.

    From: /tf/active/vicechatdev/CDocs/utils/document_processor.py
← Back to Browse