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!