Recursive merge dictionaries – Python

I recently worked on a python project and noticed a situation where I needed two dictionaries to be merged recursively. There were some easy and simple solutions, but they would not have expected results or the dictionaries were not merged recursively or merged dicts would not properly override values. So I thought to write one myself. Here I’ll demonstrate how to combine two python dictionaries where merged dict will have corresponding values from both first and second dicts with second having precedence over the first.

Python merge dictionaries

Following code can be used to recursively merge two dicts.

Example:
dict1 = { ‘project’ : { ‘res’ : { ‘name’ : ‘resource’, ‘number’ : ‘1’ } } }
dict2 = { ‘project’ : { ‘res’ : { ‘desc’ : ‘description’, ‘number’ : ‘2’ } } }
merged = { ‘project’ : { ‘res’ : { ‘name’ : ‘resource’, ‘desc’ : ‘description’, ‘number’ : ‘2’ } } }

def _merge_dictionaries(dict1, dict2):
    """
    Recursive merge dictionaries.

    :param dict1: Base dictionary to merge.
    :param dict2: Dictionary to merge on top of base dictionary.
    :return: Merged dictionary
    """
    for key, val in dict1.items():
        if isinstance(val, dict):
            dict2_node = dict2.setdefault(key, {})
            _merge_dictionaries(val, dict2_node)
        else:
            if key not in dict2:
                dict2[key] = val

    return dict2

Thats working code! But I also want to show here what didn’t work for me. I initially tried with `dict.update` and spread operators. Bot both of them failed to update the dicts recursively.

Leave a Reply


Your email address will not be published. Required fields are marked *