Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

python recursively merge dictionaries

# Example usage:
# Say you have the following dictionaries and want to merge dict_b into dict_a
dict_a = {"ABC": {"DE": {"F": "G"}}}
dict_b = {"ABC": {"DE": {"H": "I"}, "JKL": "M"}} 

def merge_nested_dictionaries(dict_a, dict_b, path=None):
    """
    recursive function for merging dict_b into dict_a
    """
    if path is None:
        path = []
    for key in dict_b:
        if key in dict_a:
            if isinstance(dict_a[key], dict) and isinstance(dict_b[key], dict):
                merge_nested_dictionaries(dict_a[key], dict_b[key], path + [str(key)])
            # if the b dictionary matches the a dictionary from here on, skip adding it
            elif dict_a[key] == dict_b[key]:
                pass
            # if the same series of keys lead to different terminal values in
            # each dictionary, the dictionaries can't be merged unambiguously
            else:
                raise Exception('Conflict at %s' % '.'.join(path + [str(key)]))
        # if the key isn't in a, add the rest of the b dictionary to a at this point
        else:
            dict_a[key] = dict_b[key]
    return dict_a

# running:
merge_nested_dictionaries(dict_a, dict_b)
# returns:
{'ABC': {'DE': {'F': 'G', 'H': 'I'}, 'JKL': 'M'}}
Comment

PREVIOUS NEXT
Code Example
Python :: unique values in dataframe column count 
Python :: picasa 
Python :: python pillow cut image in half 
Python :: roman to integer 
Python :: finding odd even python 
Python :: sqlalchemy filter between dates 
Python :: can is slice list with list of indices python 
Python :: python selenium click element 
Python :: how to make python open a program/desktop app 
Python :: merge dicts python 
Python :: how to sort a list descending python 
Python :: Python program to draw hexagon 
Python :: NumPy unique Example Get the unique rows and columns 
Python :: python import timezone 
Python :: What is role of ALLOWED_HOSTs in Django 
Python :: sort rows by values dataframe 
Python :: python 7zip extract 
Python :: Python NumPy swapaxis Function Example 
Python :: assign a same value to 2 variables at once python 
Python :: python argparse lists flags as optional even with required 
Python :: python find file name 
Python :: convert all colnames of dataframe to upper 
Python :: python delete element from list 
Python :: how to get the link of an image in selenium python 
Python :: if name == main 
Python :: discord.py find voice channel by name 
Python :: disbale tkinter textbox 
Python :: how to use input in python 
Python :: python arrays 
Python :: django createssuperuser 
ADD CONTENT
Topic
Content
Source link
Name
1+8 =