如何检查变量是否是Python中的字典? [英] How to check if a variable is a dictionary in Python?
本文介绍了如何检查变量是否是Python中的字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您如何检查变量是否是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)
推荐答案
您可以使用if type(ele) is dict
或使用 isinstance(ele, dict)
,如果您将dict
子类化,则将起作用:
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)
这篇关于如何检查变量是否是Python中的字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文