1

I have two nested dictionaries (loaded from json) and need to check if the keys in one already exist in the other, and if not add them.

Example json:

eg_dict = {
    "A":
    {
        "A1":
        {
            "A1a": "bird",
            "A1b": true,
            "A1c": false
        },
        "A2":
        {
            "A2a":
            {
                "A2a1": "parrot",
                "A2a2":
                {
                    "enabled": true
                }
            }
        }
    },
    "B":
    {
        "B1":
        {
            "B1a": "Reptile"
        },
        "A2":
        {
            "A2a":
            {
                "A2a2":
                {
                    "enabled": true
                }
            }
        }
     }
}

I need to add A1 and A2a1 to B.

I've tried Check if a nested dictionary is a subset of another nested dictionary but it's not doing quite what I need.

I started trying to pass the parent key through a recursive function, but as I don't know how deep the nesting goes, this seems like a dead end?

def get_all_values(pkey, nested_dictionary):
#I don't think passing p(arent)key to the function gets me anywhere
    for key, value in nested_dictionary.items():
        if type(value) is dict:
            print(key, ":", value)
            get_all_values(pkey, value)
        else:
            print(key, ":", value)


def get_json(file, chartname):
    #print(chartname)
    with open(file) as file:
        file= json.load(file)
    b = file['B']
    #Can do it if I know the key I want to copy
    if 'A1' in file['A'].keys():
            b['A1'] = file['A']['A1']
    #Trying a function to get all missing keys from A
    get_all_values(key=None, file['B'])
    b = json.dumps(b)
    return b

First time posting on stackoverflow, so help on improving my question welcome too!

JakeH
  • 13
  • 2

1 Answers1

0

A recursive solution to build a dictionary from A and B, where values of A have precedence over values of B:

a_dict = eg_dict['A']
b_dict = eg_dict['B']

print(a_dict)
# {'A1': {'A1a': 'bird', 'A1b': True, 'A1c': False}, 'A2': {'A2a': {'A2a1': 'parrot', 'A2a2': {'enabled': True}}}}
print(b_dict)
# {'B1': {'B1a': 'Reptile'}, 'A2': {'A2a': {'A2a2': {'enabled': True}}}}

def extend_dict(primary_dict, secondary_dict):
    result_dict = {}
    for k in set(primary_dict.keys()).union(set(secondary_dict.keys())):
        if (k in primary_dict.keys() and k in secondary_dict.keys()) and (isinstance(primary_dict[k], dict) and isinstance(secondary_dict[k], dict)):
            result_dict.update({k: extend_dict(primary_dict[k], secondary_dict[k])})
        elif k in primary_dict.keys():
            result_dict.update({k: primary_dict[k]})
        elif k in secondary_dict.keys():
            result_dict.update({k: secondary_dict[k]})
    return result_dict

extended = extend_dict(a_dict, b_dict) 
print(extended)
# {'B1': {'B1a': 'Reptile'}, 'A2': {'A2a': {'A2a2': {'enabled': True}, 'A2a1': 'parrot'}}, 'A1': {'A1a': 'bird', 'A1b': True, 'A1c': False}}

If you want to switch the precedence, just switch A and B, such that extended = extend_dict(b_dict, a_dict).

Let me know if this is what you are looking for.

André
  • 1,034
  • 9
  • 19