Awesome!
Completion rate improved to 4.17SectionΒ 5. ChapterΒ 2
single
Challenge: Recursive File Search
Swipe to show menu
Working with Nested Dictionaries
Dictionaries can store other dictionaries, which is useful for representing hierarchical data like a file system.
- Keys are file or folder names;
"file"means the item is a file;- A nested dictionary means the item is a folder.
Use items() to iterate through keyβvalue pairs.
1234567file_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 whether a value represents a folder:
12345678910file_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
To check whether a specific file exists in a nested dictionary, implement a recursive file_exists function:
- Loop through the dictionary with
items(). - If
contentis"file"andnamematchestarget, returnTrue. - If
contentis a folder (isinstance(content, dict)), callfile_existsrecursively. - If the recursive call returns
True, propagateTrue. - If nothing matches after checking all levels, return
False.
Solution
Everything was clear?
Thanks for your feedback!
SectionΒ 5. ChapterΒ 2
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat