Home > Mobile >  Search for dictionary value and output "address" in python
Search for dictionary value and output "address" in python

Time:07-10


I have a list of dictionaries, with a list value (of dictionaries), etc etc.

filesystem = [
    {
        "type":"dir",
        "name":"examples",
        "ext":"",
        "contents":[
            {
                "type":"file",
                "name":"text_document",
                "ext":"txt",
                "contents":"This is a text document.\nIt has 2 lines!"
            }
        ]
    },
    {
        "type":"file",
        "name":"helloworld",
        "ext":"py",
        "contents":"print(\"Hello world\")"
    }
]

I need a way to search for a dictionary. For example, I want to get the examples folder. I want to write a path: /examples and search for the directory the path directs to. This needs to work with nested directories as well.
I have tried to match to a dictionary using wildcards:


target = {
    "type":"dir",
    "name":currentSearchDir,
    "ext":"",
    "contents":*
}

if currentSearch == target:
    print("found")

but, of course, it doesn't work. Thanks.

CodePudding user response:

Here is a recursive search:

filesystem = [
    {
        "type":"dir",
        "name":"examples",
        "ext":"",
        "contents":[
            {
                "type":"file",
                "name":"text_document",
                "ext":"txt",
                "contents":"This is a text document.\nIt has 2 lines!"
            }
        ]
    },
    {
        "type":"file",
        "name":"helloworld",
        "ext":"py",
        "contents":"print(\"Hello world\")"
    }
]

def search(data, name):
    for entry in data:
        if entry['name'] == name:
            return entry
        if isinstance( entry['contents'], list ):
            sub = search( entry['contents'], name )
            if sub:
                return sub
    return None

print( search( filesystem, "examples" ) )
print( search( filesystem, "text_document" ) )

Output:

{'type': 'dir', 'name': 'examples', 'ext': '', 'contents': [{'type': 'file', 'name': 'text_document', 'ext': 'txt', 'contents': 'This is a text document.\nIt has 2 lines!'}]}
{'type': 'file', 'name': 'text_document', 'ext': 'txt', 'contents': 'This is a text document.\nIt has 2 lines!'}
  • Related