Bird
0
0

You want to read a file and create a dictionary where keys are line numbers (starting at 1) and values are the lines without newline characters. Which code correctly does this?

hard📝 Application Q8 of 15
Python - File Handling Fundamentals
You want to read a file and create a dictionary where keys are line numbers (starting at 1) and values are the lines without newline characters. Which code correctly does this?
Awith open('file.txt') as f: d = {line: i for i, line in enumerate(f)}
Bwith open('file.txt') as f: d = {i: line for i, line in enumerate(f.readlines())}
Cwith open('file.txt') as f: d = dict(enumerate(f))
Dwith open('file.txt') as f: d = {i+1: line.strip() for i, line in enumerate(f)}
Step-by-Step Solution
Solution:
  1. Step 1: Use enumerate to get line numbers starting at 0

    enumerate(f) gives (0, line), (1, line), ...
  2. Step 2: Adjust keys to start at 1 and strip newlines

    Use i+1 for keys and line.strip() to remove newlines.
  3. Step 3: Build dictionary comprehension

    {i+1: line.strip() for i, line in enumerate(f)} creates desired dictionary.
  4. Final Answer:

    with open('file.txt') as f: d = {i+1: line.strip() for i, line in enumerate(f)} -> Option D
  5. Quick Check:

    Correct dict comprehension with line numbers and strip [OK]
Quick Trick: Use enumerate and strip() inside dict comprehension [OK]
Common Mistakes:
  • Not adding 1 to index
  • Not stripping newline
  • Using line as key instead of number

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes