Home > database >  How to check if a return object is a dictionary in python
How to check if a return object is a dictionary in python

Time:11-15

I have written a function f(x) that either returns a dictionary or an error message.

def myfunc():
    try:
       return dictionary
    except BaseException as e:
       return e

return_value = myfunc()

if return_value a dictionary:
    do this
else:
    do that 

I need to detect the type of return in another function f(y) which calls f(x).

How do I do that?

thanks in advance

CodePudding user response:

isinstance(return_value, dict)

CodePudding user response:

You can check a value's type as follows:

if type(return_value) == dict:
    print("It is a dictionary.")
else:
    pinrt("It is not a dictionary")

There are several ways to check a type of value, see: How to check if type of a variable is string?

CodePudding user response:

Your example does not follow normal best practices, but you would do the following:

if type(return_value) is dict:

or

if isinstance(return_value, dict):
  • Related