Challenge: Recursive File Search
Working with Nested Dictionaries
In Python, dictionaries can contain other dictionaries. This is useful for representing hierarchical structures like a file system.
To navigate a dictionary:
Use items()
to iterate through all key-value pairs:
file_system = { "home": { "resume.pdf": "file", "notes.txt": "file" }, "etc": { "config.yaml": "file" } } for name, content in file_system.items(): print(name, "->", content)
Use isinstance(content, dict) to check if a value is itself a dictionary (i.e., a folder, not a file):
file_system = { "home": { "resume.pdf": "file" }, "config.yaml": "file" } for name, content in file_system.items(): if isinstance(content, dict): print(name, "is a folder") else: print(name, "is a file")
Task
Swipe to start coding
Imagine needing to check whether a specific file exists within a nested dictionary structure representing a file system. Implement a function file_exists
that recursively navigates through folders (dictionary objects) and searches for a file (represented by the string "file"
). Return True
if the file is found; otherwise, return False
.
- Use a
for
loop to iterate through all elements of thefile_system
dictionary using theitems()
method. This retrieves the key (name
) and the value (content
). - Check if
content
is a file (i.e., the string"file"
) and ifname
matchestarget
(the name of the file being searched for). - If both conditions are met, return
True
, indicating that the file has been found. - If content is not a file, check whether it is a folder.
Use the
isinstance()
function, passingcontent
as the first argument anddict
as the second (which checks if the element is a dictionary). - If
content
is a folder, callfile_exists
recursively with the necessary parameters to continue searching inside it. - If the recursive call returns
True
, the file has been found, so returnTrue
. - If no matches are found after checking all folders and files, return
False
.
Solution
Everything was clear?
Thanks for your feedback!
SectionΒ 5. ChapterΒ 2