Sunday, September 2, 2018

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)

Answer



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)


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...