简体   繁体   中英

How to efficiently look a value in a multi level dictionary in python

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM