简体   繁体   English

遍历嵌套的字典对象并获取 Python 中特定对象的值

[英]Iterate through nested Dictionary Object and get the value of specific object in Python

I want to get the value of all ObjectId from this Dictionary which is a combination of list and dictionary.我想从这个字典中获取所有ObjectId的值,它是列表和字典的组合。 The required answer to me is -> 2, 2, [[ "Value is 1"], ""], 3, 2我需要的答案是 -> 2, 2, [[ "Value is 1"], ""], 3, 2

My solution to get the ObjectId.我获取 ObjectId 的解决方案。 This was only giving me the value of inner ObjectId.这只是给了我内部 ObjectId 的值。 Want to get the values of all ObjectId whether the value is int or list etc.想要获取所有 ObjectId 的值,无论值是 int 还是 list 等。

for key in dictObj:
    if key == "RESULT":
        if (type(dictObj[key])== list):
            for list in dictObj[key]:
                for key,value in list.items():
                    while(True):
                        if (type(value)==dict) and value:
                            for key1,value1 in value.items():
                                value = value1
                                key = key1
                        elif (key=="ObjectId"):
                            print(value)
                            break
                        else:
                            break

Dictionary Object is字典对象是

dictObj =  {
            "Id": 1,
            "RESULT": [
                {
                    "Check": {
                        "checkinstance": {
                            "ObjectId": 2,
                            "Class": "Base"
                        }
                    },
                    "Class": "Base"
                },
                {
                    "ObjectId": 2,
                    "Class": "Base",
                    "Start": {}
                },
                {
                    "Display": {
                        "part": {
                            "Class": "Base",
                            "ObjectId": [
                                [
                                    "Value is 1"
                                ],
                                ""
                            ]
                        },
                        "load": {
                            "ObjectId": 3,
                            "Class": "Base"
                        }
                    },
                    "Class": "Base"
                },
                {
                    "ObjectId": 2,
                    "Class": "Base",
                    "Stop": {}
                }
            ]
        }

This code makes no assumption of the structure of the input object, obj (it can be a dictionary or list):这段代码不假设输入对象obj的结构(它可以是字典或列表):

obj   = {
            "Id": 1,
            "RESULT": [
                {
                    "Check": {
                        "checkinstance": {
                            "ObjectId": 2,
                            "Class": "Base"
                        }
                    },
                    "Class": "Base"
                },
                {
                    "ObjectId": 2,
                    "Class": "Base",
                    "Start": {}
                },
                {
                    "Display": {
                        "part": {
                            "Class": "Base",
                            "ObjectId": [
                                [
                                    "Value is 1"
                                ],
                                ""
                            ]
                        },
                        "load": {
                            "ObjectId": 3,
                            "Class": "Base"
                        }
                    },
                    "Class": "Base"
                },
                {
                    "ObjectId": 2,
                    "Class": "Base",
                    "Stop": {}
                }
            ]
        }

def filter(obj):
    if isinstance(obj, list):
        for item in obj:
            filter(item)
    elif isinstance(obj, dict):
        if "ObjectId" in obj:
            print(obj["ObjectId"])
        for v in obj.values():
            if isinstance(v, (list, dict)):
                filter(v)

filter(obj)

Prints:印刷:

2
2
[['Value is 1'], '']
3
2

Python Demo Python 演示

If you don't want to print the values but instead accumulate them into a list then:如果您不想打印值而是将它们累积到列表中,则:

def filter2(obj):
    if isinstance(obj, list):
        for item in obj:
            yield from filter2(item)
    elif isinstance(obj, dict):
        if "ObjectId" in obj:
            yield obj["ObjectId"]
        for v in obj.values():
            if isinstance(v, (list, dict)):
                yield from filter2(v)

print(list(filter2(obj)))

Prints:印刷:

[2, 2, [['Value is 1'], ''], 3, 2]

Pyhon Demo pyhon 演示

You can have a recursive function which searches all keys in a dict and then all the keys of the values which are also dict s:您可以使用递归函数搜索dict所有键,然后搜索也是dict的值的所有键:

# dictObj as in post

def findKey(key, d, result):
    for k,v in d.items():
        if k == key:
            result.append(v)
        if isinstance(v,dict):
            findKey(key, v, result)



result = []

for key in dictObj:
    if key == "RESULT":
        if (type(jsonObj[key])== list):
            for d in jsonObj[key]:
                findKey('ObjectId', d, result)

print(result)

Output:输出:

[2, 2, [[ "Value is 1"], ""], 3, 2]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM