0

I have a dictionary that looks like this:

d = {'dev':
        {<dev1>:
             {'mod':
                 {<mod1>:
                     {'port': [1, 2, 3]
                            }
                  }
              }
         <dev2>:
             {'mod':
                 {<mod3>:
                       {'port': [] }
                 }
             }
       }
  }

I want to be able to write a function, such that if i provide a search object such as 'mod1', it provides me the parent key as 'dev1'.

I have searched all over and tried a bunch of things, but couldnt seem to get this to work. Any help will be appreciated!

I have tried the stuff mentioned at the link below:

Python--Finding Parent Keys for a specific value in a nested dictionary

Find a key in a python dictionary and return its parents

Community
  • 1
  • 1
nsJHDM
  • 21
  • 1
  • 2
  • 7
  • Can you show us some of the things you've tried? – larsks Jul 24 '15 at 20:23
  • 3
    What did you try? You will have to manually walk the entire dictionary tree looking for your target key. Also, there is no guarantee that it will occur only once. – BrenBarn Jul 24 '15 at 20:23
  • What's wrong with the solutions you linked? – Morgan Thrapp Jul 24 '15 at 20:26
  • Edits show what I have tried. @BrenBarn I understand I have to walk the dict to get the target key. But is there any way to retrieve the parent key? I understand there will be duplicates. But is there a way to get a list of the ones that contain this key? – nsJHDM Jul 24 '15 at 20:27
  • @MorganThrapp - They do not seem to work for the dict structure that I have. I do not get anything back when I tried them out. – nsJHDM Jul 24 '15 at 20:28
  • @MorganThrapp - any suggestions on what I might need to tweak in those solutions I posted or how else I need to do this traversal? – nsJHDM Jul 24 '15 at 20:32
  • @nsJHDM You need to show a real MCVE (http://stackoverflow.com/help/mcve). Then maybe we can tell you what's wrong with what you're doing. – CrazyCasta Jul 24 '15 at 20:40

1 Answers1

1

This should work:

def find_parent_keys(d, target_key, parent_key=None):
  for k, v in d.items():
    if k == target_key:
      yield parent_key
    if isinstance(v, dict):
      for res in find_parent_keys(v, target_key, k):
        yield res

Usage:

d = {
  'dev': {
    'dev1': {
      'mod': {
        'mod1': {'port': [1, 2, 3]},
      },
    },
    'dev2': {
      'mod': {
        'mod3': {'port': []},
      },
    },
  },
}

print list(find_parent_keys(d, 'mod'))
print list(find_parent_keys(d, 'dev'))

Output:

['dev2', 'dev1']
[None]
Claudiu
  • 224,032
  • 165
  • 485
  • 680
  • 1
    Thanks! looping through this and recursively calling this function should get me what I want! :) – nsJHDM Jul 24 '15 at 20:52