Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, I'd like it to loop through the values in the dictionary until 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)     else:         print(k, ' ', v) 
like image 694
Riley Avatar asked Aug 10 '14 19:08

Riley


People also ask

How do I check if a string is in a dictionary Python?

Use get() and Key to Check if Value Exists in a Dictionary 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.

How do you check if a word is in a dictionary Python?

To simply check if a key exists in a Python dictionary you can use the in operator to search through the dictionary keys like this: pets = {'cats': 1, 'dogs': 2, 'fish': 3} if 'dogs' in pets: print('Dogs found!') # Dogs found! A dictionary can be a convenient data structure for counting the occurrence of items.

How do you check if a value is in a list of dictionaries Python?

Use any() & List comprehension to check if a value exists in a list of dictionaries.

How do you check the type of a variable in Python?

To check the data type of variable in Python, use the type() method. The type() is a built-in Python method that returns the class type of the argument(object) passed as a parameter. You place the variable inside a type() function, and Python returns the data type.


1 Answers

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 element in d.values():     if isinstance(element, dict):        for k, v in element.items():            print(k,' ',v) 
like image 129
Padraic Cunningham Avatar answered Oct 09 '22 12:10

Padraic Cunningham