简体   繁体   中英

How to get a dictionary and all its elements by key?

I have a structure like this:

{
    "content": "Name 1", 
    "name": "directory", 
    "decendent": [
         {
            "content": "Name 2", 
            "name": "subdirectory", 
            "decendent": None
        }, 
        {
            "content": "Name 3", 
            "name": "subdirectory_two", 
            "decendent": [
                {
                    "content": "Name 4", 
                    "name": "subsubdirectory", 
                    "decendent": None
                }
            ]
        }
    ]
}

I have to look for the name (name is a string and unique), and if I found it - save the whole dictionary in other variable. Eg:

I'm looking for "subdirectory", i should get:

       {
            "content": "Name 2", 
            "name": "subdirectory", 
            "decendent": None
        }

and save it in the variable.

How to perform this search in Python?

You can use a recursive function checking the name of the current dictionary, and if that name matches return the dictionary, and otherwise try the "descendants", if any, and return if those have a match.

def find_name(d, name):
    if d["name"] == name:
        return d
    for d2 in d["decendent"] or []:
        res = find_name(d2, name)
        if res:
            return res

Example:

>>> dictionary = { your dictionary }
>>> print find_name(dictionary, "subdirectory")
{'content': 'Name 2', 'name': 'subdirectory', 'decendent': None}

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