简体   繁体   中英

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. The required answer to me is -> 2, 2, [[ "Value is 1"], ""], 3, 2

My solution to get the ObjectId. This was only giving me the value of inner ObjectId. Want to get the values of all ObjectId whether the value is int or list etc.

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   = {
            "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

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

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:

# 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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