1

How to check if variable is a python dictionary?

for k,v in dict.items():
    if type(v)==dict:
        print('This is a dictionary')

This code is not working

Edited:

Solved. type(v) is working. I made mistake when used name 'dict' for my dictionary.

DeepSpace
  • 153
  • 1
  • 2
  • 11

3 Answers3

8

To properly check if v is an instance of a dict you can use isinstance:

for k,v in your_dict.items():
    if isinstance(v, dict):
        print('This is a dictionary')

Note: Change your variable name 'dict' to something else, as you're masking the buit-in name

yatu
  • 86,083
  • 12
  • 84
  • 139
4

To begin with, never name your variables as python keywords, so don't use dict as a python variable name, since it is replacing the python built-in keyword dict. Instead use something like my_dict

You should consider using isinstance to check if a variable is a dictionary, instead of type

From the docs of type:

The isinstance() built-in function is recommended for testing the type of an object, because it takes subclasses into account.

Also since you are only using values, consider only iterating on them using my_dict.values()

for v in my_dict.values():
    if isinstance(v, dict):
        print('This is a dictionary')
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
0

It is better to use isinstance(object, classinfo) than checking if type(object) == classinfo

for k,v in dict.items():
    print(isinstance(v, dict))
Relandom
  • 1,029
  • 2
  • 9
  • 16