merge_dicts()
Merge two dictionaries into a new dictionary.
Usage
merge_dicts(
a,
b,
)Creates a new dictionary containing all key-value pairs from both a and b. When keys overlap, values from b take precedence.
Parameters
a: dict-
The base dictionary.
b: dict-
The dictionary whose values take priority on conflict.
Returns
dict-
A new dictionary containing the merged key-value pairs.
Notes
The merge algorithm works in two phases. First, a shallow copy of a is created using dict.copy(). Then, all entries from b are inserted into the copy using dict.update().
This means that the original dictionaries a and b are never modified. However, because only a shallow copy is made, mutable values (such as lists or nested dicts) are shared between the original and the merged result.
If you need a deep merge where nested structures are also merged recursively, consider using copy.deepcopy() on the result or implementing a custom recursive merge function.
The time complexity is O(len(a) + len(b)) since both the copy and update operations are linear.
Examples
>>> merge_dicts({"x": 1}, {"y": 2})
{'x': 1, 'y': 2}>>> merge_dicts({"x": 1}, {"x": 99})
{'x': 99}