Parse a Requirements File
Beginner · Write the code · from Python Virtual Environments and pip: A Practical Guide
From the lesson: Python Virtual Environments and pip: A Practical Guide
Imagine you're a carpenter working on two different projects. One needs tiny finishing nails and the other needs heavy-duty bolts. You wouldn't dump all your hardware into one toolbox - you'd have separate toolboxes so the right parts are always ready for the right job.
Read the lessonWrite a function called parse_requirements(text) that takes a string representing a requirements.txt file (one package per line in the format name==version). Return a dictionary mapping package names to their versions. Ignore empty lines and lines starting with #.
What Check runs
Your code runs first, then each of these lines. The output must match exactly.
| Runs | Expected output |
|---|---|
| reqs = 'flask==3.0.0\nrequests==2.31.0\npandas==2.1.4' result = parse_requirements(reqs) for pkg in sorted(result): print(f'{pkg}=={result[pkg]}') | flask==3.0.0 pandas==2.1.4 requests==2.31.0 |
| reqs = '# Core deps\nflask==3.0.0\n\n# Utils\nclick==8.1.7' result = parse_requirements(reqs) for pkg in sorted(result): print(f'{pkg}=={result[pkg]}') | click==8.1.7 flask==3.0.0 |
More Virtual Environment exercises
- Fix the Dependency ResolverIntermediate
- Predict the Environment CheckIntermediate
- Build a Virtual Environment ManagerAdvanced
All Python exercises · 50 practice problems · Modules & Packaging quiz