I have a nested dictionary. And I would like to extract a sub dictionary based on a certain attribute: Here is a simpler version of my dictionary:
subdata = {
"id": 997,
"acronym": "root",
"color_hex_triplet": "FFFFFF",
"children": [
{
"id": 8,
"acronym": "grey",
"color_hex_triplet": "BFDAE3",
"children": [
{
"id": 567,
"acronym": "CH",
"color_hex_triplet": "B0F0FF",
"children": [
{
"id": 688,
"acronym": "CTX",
"color_hex_triplet": "B0FFB8",
"children": [
{
"id": 695,
"acronym": "CTXpl",
"color_hex_triplet": "70FF70",
"children": [
{
"id": 315,
"acronym": "Isocortex",
"color_hex_triplet": "70FF71",
"children": [
{
"id": 184,
"acronym": "FRP",
"color_hex_triplet": "268F45",
"children": [
{
"id": 68,
"acronym": "FRP1",
"color_hex_triplet": "268F45",
"children": []
},
{
"id": 69,
"acronym": "FRP2",
"color_hex_triplet": "268F45",
"children": []
}]}]}]}]}]]}]}]}
And based on e.g. "acronym": "FRP" I want to get that certain dictionary and all its children like this:
region_dict = {
"id": 184,
"acronym": "FRP",
"color_hex_triplet": "268F45",
"children": [
{
"id": 68,
"acronym": "FRP1",
"color_hex_triplet": "268F45",
"children": []},
{"id": 69,
"acronym": "FRP2",
"color_hex_triplet": "268F45",
"children": []
}]}
I tried the following code (from Aplet123's suggestion), but it does not seem to return the dictionary. It only returns True. Am I doing something wrong?
def get_parent_dict(dic, reg):
if dic['acronym'] == reg:
return dic
for child in dic["children"]:
result = get_parent_dict(child, reg) is not None
if result is not None:
return result
return None # not technically needed
f = open(json_path)
data = json.load(f)
subdata = data['msg'][0] #this is a nested dictionary
region_dict = get_parent_dict(subdata, "FRP")