-2

Let's say I have a dictionary called my_dic:

my_dict = {'a': {'spam': {'foo': None, 'bar': None, 'baz': None},'eggs': None}, 'b': {'ham': None}}

Then if I input spam, it should return a, and if I input bar it should return spam. If I input b, it should return None. Basically getting the parent of the dictionary.

How would I go about doing this?

Adam Albu
  • 5
  • 2
  • 1
    What have you tried, where are you stuck? You’ll need a *recursive* function for starters… – deceze Dec 03 '22 at 10:59
  • I think you are looking for something like [this](https://stackoverflow.com/questions/48314755/find-keys-in-nested-dictionary). – curioso Dec 03 '22 at 11:01
  • [Check out](https://stackoverflow.com/questions/2273691/pythonic-way-to-reverse-nested-dictionaries) this for flipping key-values in a dictionary. Maybe you can just keep track of the relationships as you add them into a separated dictionary. Maybe you would benefit more by creating an [UserDict](https://docs.python.org/3/library/collections.html#collections.UserDict). What you want to achieve? What is your goal/tasks from hindsight? – Dimitar Popchev Dec 03 '22 at 11:03

1 Answers1

0

A simple recursive function, which returns the current key if needle in v is true; needle in v simply testing if the key exists in the associated value:

my_dict = {'a': {'spam': {'foo': None, 'bar': None, 'baz': None},'eggs': None}, 'b': {'ham': None}}

def get_parent_key(d: dict, needle: str):
    for k, v in d.items():
        if isinstance(v, dict):
            if needle in v:
                return k
            
            if found := get_parent_key(v, needle):
                return found
                
print(get_parent_key(my_dict, 'bar'))
deceze
  • 510,633
  • 85
  • 743
  • 889