Riley Riley -4 years ago 193
Python Question

How to check if a variable is a dictionary in python

How would you check if a variable is a dictionary in python?

For example id like it to loop through the values in the dictionary till it finds a dictionary then loop through the one it finds:

dict = {'abc':'abc','def':{'ghi':'ghi','jkl':'jkl'}}
for k, v in dict.iteritems():
if ###check if v is a dictionary:
for k, v in v.iteritems():
print(k,' ',v)
print(k,' ',v)

Any help would be greatly appreciated.

Answer Source

You could use if type(ele) is dict or use isinstance(ele, dict) which would work if you had subclassed dict:

d = {'abc':'abc','def':{'ghi':'ghi','jkl':'jkl'}}
for ele in d.values():
    if isinstance(ele,dict):
       for k, v in ele.items():
           print(k,' ',v)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download