Challenge: Recursive File Search
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")
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
Thanks for your feedback!
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Can you explain how to add a new file or folder to this nested dictionary?
How can I recursively print all files and folders in this structure?
What does the output of these code samples look like?
Awesome!
Completion rate improved to 4.17
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")
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
Thanks for your feedback!
single