Home > Software engineering >  How to check if a specific type exists in a python dictionary?
How to check if a specific type exists in a python dictionary?

Time:09-28

How to check if a specific type exists in a dictionary? No matter what level this is in. I want to do the search both in the keys and values set.

For example, I want to find out the dictionary key that is a np.int64.

CodePudding user response:

I'd loop over the dict with a for loop and check one-by-one:

some_dict = {1:"one",
             2:"Two",
             3:"Three",}

for key, value in some_dict.items():
     if isinstanceof(value, np.int64):
         print("Found one! it is {}:{}".format(key, value))

This wil check every one, one-by-one. Here is a list of sources to look into. That way you'll know why it works:

CodePudding user response:

You can use recursion for nested dicts

def recur(dct, type_ref):
    for k,v in dct.items():
        if isinstance(v, type_ref) or isinstance(k, type_ref):
            print(k,v)
            return True
        if isinstance(v, dict):
            return recur(v, type_ref)
    return False
# dct = input dict, type_ref = type you want to match

Not sure if this is exactly what you want since you haven't provided much information

  • Related