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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25231989/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:54:37  来源:igfitidea点击:

How to check if a variable is a dictionary in Python?

pythondictionary

提问by Riley

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

你如何检查变量是否是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)

采纳答案by Padraic Cunningham

You could use if type(ele) is dictor use isinstance(ele, dict)which would work if you had subclassed dict:

如果你有子类,你可以使用if type(ele) is dict或使用isinstance(ele, dict)which 会起作用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)

回答by CodeMantle

The OP did not exclude the starting variable, so for completeness here is how to handle the generic case of processing a supposed dictionary that may include items as dictionaries.

OP 没有排除起始变量,所以为了完整起见,这里是如何处理处理可能包含项目作为字典的假设字典的一般情况。

Also following the pure Python(3.8) recommended wayto test for dictionary in the above comments.

同样遵循纯 Python(3.8)推荐的方法来测试上述注释中的字典。

from collections.abc import Mapping

dict = {'abc': 'abc', 'def': {'ghi': 'ghi', 'jkl': 'jkl'}}

def parse_dict(in_dict): 
    if isinstance(in_dict, Mapping):
        for k, v in in_dict.items():
            if isinstance(v, Mapping):
                for k, v in v.items():
                    print(k, v)
            else:
                print(k, v)

parse_dict(dict)