Search code examples
python-3.xdictionaryhierarchy

Combine two hierarchy dictionaries (Python3)


I have two hierarchy dictionaries that I need to combine into one. Dictionaries a & b only share a common root node (e.g. the CEO of the organisation), otherwise there is no overlap between them (e.g. a and b below are two separate lines of the business).

a = {'parent': '', 'name': 'CEO', 'children': [{'parent': 'CEO', 'name': 'Dir1'}]}
b = {'parent': '', 'name': 'CEO', 'children': [{'parent': 'CEO', 'name': 'Dir2'}]}

This is what the combined dictionary needs to look like, but how?

{'parent': '', 'name': 'CEO', 'children': [{'parent': 'CEO', 'name': 'Dir1'},{'parent': 'CEO', 'name': 'Dir2'}]}

I have tried

def Merge(dict1, dict2): 
    return(dict2.update(dict1)) 

def Merge(dict1, dict2): 
    res = {**dict1, **dict2} 
    return res 

...but neither work for this due to the hierarchy nature of the dictionaries I assume. I also tried this, but no success: SO link


Solution

  • I think this code should return what you need:

    a = {'parent': '', 'name': 'CEO', 'children': [{'parent': 'CEO', 'name': 'Dir1'}]}
    b = {'parent': '', 'name': 'CEO', 'children': [{'parent': 'CEO', 'name': 'Dir2'}]}
    
    def Merge(dictionaries):
      children = []
      for d in dictionaries:
        children = children + d['children']
      return children
    
    children = Merge([a,b])
    
    new_dictionary = {'parent': '', 'name': 'CEO', 'chilren': children}
    
    print(new_dictionary)
    

    which will give you this:

    {'parent': '', 'name': 'CEO', 'chilren': [{'parent': 'CEO', 'name': 'Dir1'}, {'parent': 'CEO', 'name': 'Dir2'}]}