Use isinstance(ele, dict), which will return true for dict objects as well as subclasses of dict, such as OrderedDict and defaultdict:

d = {'abc': 'abc', 'def': {'ghi': 'ghi', 'jkl': 'jkl'}}
for element in d.values():
    if isinstance(element, dict):
       for k, v in element.items():
           print(k, ' ', v)

You can do if type(ele) is dict if you want to check strictly for instances of dict and not subclasses of it, though this is generally not recommended.

Answer from Padraic Cunningham on Stack Overflow
Top answer
1 of 5
532

Use isinstance(ele, dict), which will return true for dict objects as well as subclasses of dict, such as OrderedDict and defaultdict:

d = {'abc': 'abc', 'def': {'ghi': 'ghi', 'jkl': 'jkl'}}
for element in d.values():
    if isinstance(element, dict):
       for k, v in element.items():
           print(k, ' ', v)

You can do if type(ele) is dict if you want to check strictly for instances of dict and not subclasses of it, though this is generally not recommended.

2 of 5
117

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

This is an excellent question, but it is unfortunate that the most upvoted answer leads with a poor recommendation, type(obj) is dict.

(Note that you should also not use dict as a variable name - it's the name of the builtin object.)

If you are writing code that will be imported and used by others, do not presume that they will use the dict builtin directly - making that presumption makes your code more inflexible and in this case, create easily hidden bugs that would not error the program out.

I strongly suggest, for the purposes of correctness, maintainability, and flexibility for future users, never having less flexible, unidiomatic expressions in your code when there are more flexible, idiomatic expressions.

is is a test for object identity. It does not support inheritance, it does not support any abstraction, and it does not support the interface.

So I will provide several options that do.

Supporting inheritance:

This is the first recommendation I would make, because it allows for users to supply their own subclass of dict, or a OrderedDict, defaultdict, or Counter from the collections module:

if isinstance(any_object, dict):

But there are even more flexible options.

Supporting abstractions:

from collections.abc import Mapping

if isinstance(any_object, Mapping):

This allows the user of your code to use their own custom implementation of an abstract Mapping, which also includes any subclass of dict, and still get the correct behavior.

Use the interface

You commonly hear the OOP advice, "program to an interface".

This strategy takes advantage of Python's polymorphism or duck-typing.

So just attempt to access the interface, catching the specific expected errors (AttributeError in case there is no .items and TypeError in case items is not callable) with a reasonable fallback - and now any class that implements that interface will give you its items (note .iteritems() is gone in Python 3):

try:
    items = any_object.items()
except (AttributeError, TypeError):
    non_items_behavior(any_object)
else: # no exception raised
    for item in items: ...

Perhaps you might think using duck-typing like this goes too far in allowing for too many false positives, and it may be, depending on your objectives for this code.

Conclusion

Don't use is to check types for standard control flow. Use isinstance, consider abstractions like Mapping or MutableMapping, and consider avoiding type-checking altogether, using the interface directly.

๐ŸŒ
Stack Abuse
stackabuse.com โ€บ python-check-if-variable-is-a-dictionary
Python: Check if Variable is a Dictionary
February 27, 2023 - In Python, we can use these two ways to check if a given variable is a Dictionary: the type() function and the is operator; and the isinstance() function
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ how-to-check-if-a-key-exists-in-a-python-dictionary
How to check if a key exists in a Python dictionary
Always check if a key exists to avoid KeyError exceptions when accessing dictionary values. ... Best practices: Choose the method that fits your needs: if-in for simplicity, get() for default values, and setdefault() for setting defaults. A dictionary is a valuable data structure in Python; it ...
๐ŸŒ
LabEx
labex.io โ€บ tutorials โ€บ python-how-to-check-if-a-variable-is-a-dictionary-in-python-559599
How to Check If a Variable Is a Dictionary in Python | LabEx
The lab then guides you through using the type() function and the isinstance() function to identify whether a variable is a dictionary. You'll create Python scripts to test these methods and observe the output, solidifying your understanding ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-test-if-element-is-dictionary-value
Python | Test if element is dictionary value - GeeksforGeeks
July 12, 2025 - The get() method returns the value for a given key if it exists in the dictionary. If the key does not exist, it returns None. You can use this behavior to check if a value exists in the dictionary by checking if it is in the list returned by ...
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ gloss_python_check_if_dictionary_item_exists.asp
Python Check if Key Exists in Dictionary
Python Dictionaries Access Items Change Items Add Items Remove Items Loop Dictionaries Copy Dictionaries Nested Dictionaries Dictionary Methods Dictionary Exercises Code Challenge Python If...Else
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ checking dictionary's key and value
Checking dictionary's key and value : r/learnpython
August 19, 2021 - Is making use of the membership operator โ€œinโ€. dict.keys() returns a set of the keys inside of the dictionary. So this is just saying if x is in that set return True, otherwise return False.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ check if any item in a list is in a dict and equal to true?
r/learnpython on Reddit: Check if any item in a list is in a dict and equal to true?
May 26, 2022 -

Hi all, I have an object with many fields and attributes that I am usually get via `getattr()`. I want to determine from a list of keys, if any are equal to true in the fastest way possible. For example:

keys = ["apple", "banana"] // Only two for example purposes
dictionary = vars(MyObjectName)
// Sample dictionary contents:
// ["apple" = false, "banana" = True, "orange" = "Hoopla]

for item in dictionary:
    if item in keys && dictionary[item]:
        return True
return False

If "banana" was false, it should return false. Likewise, if "apple" was true and "banana" is false, it would still return True. If both were false, it would return false.

Is there a more efficient means than looping? Something like getattr() accepting a list would be great.

Find elsewhere
๐ŸŒ
Flexiple
flexiple.com โ€บ python โ€บ check-if-key-exists-in-dictionary-python
How to check if a key exists in a Python Dictionary? - Flexiple
To check if a key exists in a Python dictionary, employ the if statement combined with the in operator.
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ check if key exists in dictionary python
Check if Key Exists in Dictionary Python - Scaler Topics
November 16, 2023 - This prevents any unwanted behavior in your Python program. You can check if a key exists in a dictionary in Python using Python in keyword. This operator returns True if the key is present in the Python dictionary.
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python
Check If a Key/Value Exists in a Dictionary in Python | note.nkmk.me
May 19, 2025 - To check whether a specific key-value pair exists in a dictionary, use the in operator with the items() method. Specify the pair as a tuple (key, value). Use not in to check that the pair is absent.
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
How to check if a dictionary element is an array - Python Help - Discussions on Python.org
July 19, 2024 - How do I make sure that [0] exists before grabbing โ€˜iconโ€™ from it ยท Now, regarding your question, here is an example that hopefully helps you to understand the concept. Note that you do not need to explicitly define the icon string in brackets as per your query.
๐ŸŒ
Vultr
docs.vultr.com โ€บ python โ€บ examples โ€บ check-if-a-key-is-already-present-in-a-dictionary
Python Program to Check if a Key is Already Present in ...
September 27, 2024 - Directly use the in keyword to check if the key exists. ... my_dict = {'a': 1, 'b': 2, 'c': 3} key_to_check = 'b' exists = key_to_check in my_dict print(f"Key '{key_to_check}' exists in dictionary: {exists}") Explain Code
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ python โ€บ python check if value in dictionary
How to Check if a Value Is in a Dictionary in Python | Delft Stack
February 2, 2024 - To start, youโ€™d want to print True if the value exists in the dictionary; otherwise, print False. Dictionaries in Python have a built-in function key(), which returns the value of the given key. At the same time, it would return None if it doesnโ€™t exist.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ how-to-check-if-a-key-exists-in-a-dictionary-in-python
How to Check if a Key Exists in a Dictionary in Python โ€“ Python Dict Has Key
June 27, 2023 - You can use the in operator to check if a key exists in a dictionary. It's one of the most straightforward ways of accomplishing the task. When used, it returns either a True if present and a False if otherwise.
๐ŸŒ
PythonForBeginners.com
pythonforbeginners.com โ€บ home โ€บ check if value exists in a dictionary in python
Check if Value Exists in a Dictionary in Python - PythonForBeginners.com
May 18, 2022 - In the except block, we catch the exception and terminate the program normally by printing the appropriate message for the user. To check if a value exists in a dictionary using the subscript notation, we will obtain the value associated with the key name in the dictionary.
๐ŸŒ
FavTutor
favtutor.com โ€บ blogs โ€บ check-key-exists-in-dictionary-python
Check if Key exists in Dictionary (or Value) with Python code
February 18, 2023 - student_dictionary = {1: "Rahul", ... of the pair. The best way to check if a value exists in a python dictionary is the values() method....
๐ŸŒ
Reddit
reddit.com โ€บ r/learnprogramming โ€บ how to check if value anywhere in dictionary?
r/learnprogramming on Reddit: How to check if value anywhere in dictionary?
April 5, 2023 -

Hi all,

Funny enough, I got stuck at this bit while working on a personal project. I have a dictionary of the form:

dict = {
    list1: [a, b, c],
    list2: [d, e, f],
    list3: [g, h],
    sub_dict: {
        list4: [i, j],
        list5: [k, l],
        list6: [m, n, o, p]
    list7: [q, r, s, t]
}

I am trying to see if an element is anywhere in this dictionary. What's the best way to do this? I have tried a nested loop but due to the fact I have a nested dictionary, it ends up "looping" through each element in the lists too and compares my search term, say "Dog" with every letter in the every word of the lists.

Any help is appreciated.

Top answer
1 of 2
3
Well this isnโ€™t a very effective dictionary for what you want to do. I would suggest something along the lines of. Dog: numberOfListDogIsIn Now we can check if itโ€™s in the dictionary! And we still know what list itโ€™s in. Hope that at least a helps you a bit.
2 of 2
2
I think the best way to check if a value is anywhere in a dictionary is to use a recursive function that can handle nested dictionaries and lists. The function should take the dictionary and the value as arguments, and return True if the value is found, or False otherwise. The function should loop through the dictionary keys and values, and check if the value matches any of them. If the value is a list, the function should loop through the list elements and check if the value matches any of them. If the value is another dictionary, the function should call itself recursively on that dictionary. Here is an example of such a function: def check_value_in_dict(dictionary, value): # Loop through the dictionary keys and values for key, val in dictionary.items(): # Check if the value matches the key or the value if value == key or value == val: return True # Check if the value is a list elif isinstance(val, list): # Loop through the list elements for element in val: # Check if the value matches the element if value == element: return True # Check if the value is another dictionary elif isinstance(val, dict): # Call the function recursively on that dictionary if check_value_in_dict(val, value): return True # Return False if the value is not found return False