Search code examples
pythondictionarydirectorypath

Check which files [dict] match with given path


I have a dict with files:

files = {
    "/test/path/file1.c": "NotImportant",
    "/test/path/file2.c": "NotImportant",
    "/other/path/filex.c": "NotImportant",
    "/different/path/filez.c": "NotImportant"
    }

I now have a dict e.g. path = '/test/path/' and I want to see which file is in this specific path. I tried it with

if path in files:
    print("found")

However this is not working for me. I solved it with a loop going through every file and checking with the same statement. Is there still another way to solve it?

My solution:

for file in files:
    if path in file:
        print("found")

Why does the statement work here and not before? I want to have a better solution instead of looping over the whole files.


Solution

  • you can you regular expression to match path.

    for example:

    path_pattern = "^{}/.*".format(path)
    for file in files:
        if re.match(path_pattern, file):
            print("Found")