I have nested dictionary like following
{
"A":
{"B":
{"C":
{"D": ['1','2','3']
}
}
},
"AA":
{"BB":
{"CC": ['11', '22']}
}
}
I have to create a new dictionary in the following format:
{"xx-A-B-C-D": ['1','2','3'], "xx-AA-BB-CC": ['11','22']}
That is, the keys of the new dictionary are the original dictionary keys concatenated with 'xx' as the prefix, and the values are the values of the original dictionary.
I am still stuck after trying out for 5 hours. Any one care to peel the onion?
The following functions are my 2 attempts.
def get_value_from_dict(dict_obj, target):
results = []
def _get_value_from_dict(obj, results, target):
if isinstance(obj, dict):
for key, value in obj.items():
if key == target:
results.append(value)
elif isinstance(value, (list, dict)):
_get_value_from_dict(value, results, target)
elif isinstance(obj, list):
for item in obj:
_get_value_from_dict(item, results, target)
return results
results = _get_value_from_dict(dict_obj, results, target)
return results
def myprint(d):
for k, v in d.items():
if isinstance(v, dict):
myprint(v)
else:
print("{0} : {1}".format(k, v))