-1

I need perform search in some dictionary structure :

dic_global = {
    'key_lev1_1': {
        'key_lev2_a': 'some_value_1',
        'key_lev2_b': 'some_value_2'
                  },
    'key_lev1_2': 'some_value_111'
}

and I need to perform recursive search for item in the whole structure so that function would return the key where the item was. so if fun found 'key_lev2_a' it returns 'key_lev1_1' - the name of enclosure the key where the dict with 'key_lev2_a' is.

is it possible ?

SWANSE
  • 9
  • 2
  • 2
    What "dictionary name" are you talking about? – khelwood Jul 03 '19 at 22:08
  • 2
    Please provide a [mcve] for your question with sample input and desired output – G. Anderson Jul 03 '19 at 22:10
  • 1
    Dictionaries don't have names. Dictionary elements have keys, but `if item in dict` searches the keys, so `item` contains the key that was found. – Barmar Jul 03 '19 at 22:11
  • To follow on from @Barmar, you can get the corresponding value with `dict[item]`. You can also skip the `if` using either `try` or else `dict.get(item)`. Finally, don't use `dict` as a variable name as you'll hide the built-in. – Dan Jul 03 '19 at 22:16
  • I think you might be looking for https://stackoverflow.com/q/8023306/5015356 – Ruben Helsloot Jul 03 '19 at 22:16
  • I edited question for more clearness now – SWANSE Jul 03 '19 at 22:53

1 Answers1

0
def find_key(obj, key):
    if key in obj:
        return obj
    for k, v in obj.items():
        if isinstance(v, dict):
            item = find_key(v, key)
            if item is not None:
                return k

(source: modified Get key by value in dictionary)

tmechen
  • 11
  • 4
  • (this wont work if the key you are looking for is in the most parent dict because of obvious reason: this one does not have a parent key.) – tmechen Jul 03 '19 at 23:09