如何检查变量是否是python中的字典 [英] How to check if a variable is a dictionary in python

查看:152
本文介绍了如何检查变量是否是python中的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查变量是否是python中的字典?

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

例如,id就像循环遍历字典中的值,直到找到一个字典循环通过它找到的:

For example id like it to loop through the values in the dictionary till 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)

任何帮助将不胜感激。

推荐答案

p>如果type(ele)是dict 或使用 ifinstance> 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆