Home > other >  How to efficiently look a value in a multi level dictionary in python
How to efficiently look a value in a multi level dictionary in python

Time:11-30

I have the below dictionary.

mapper = { "Pog-345": {"DFH":['13062519','13063013','13063543','13072434','13123190']}
 ,"Pog-347": {"Hetive":['82722892'],"TFH":['14326471','50059137','54250307','15681953','76433609'],} 
 , "Poh-45": {}  }

How can I check a key is in the dictionary. For example, I want to know this key "Poh-45" is inside the dictionary. (Since my actual dictionary is way bigger than this I need some efficient code) How can I do that in the multilevel dictionary? If the key is in there and not empty I want to do some calculations, if the key isn't there I want to go to the next step. Can someone give me an idea, please? Anything is appreciated thanks in advance.

CodePudding user response:

Use recursion:

def check_key(d, k):
    for i in d:
        if isinstance(i, dict):
            return check_key(d)
        elif i == k:
            return True
    return False

Example:

>>> print(check_key(mapper, 'Pog-347'))
True
>>> print(check_key(mapper, 'og-347'))
False
  • Related