Bird
Raised Fist0

How can you write a dictionary data = {'a': 1, 'b': 2} to a file so that each key-value pair is on its own line in the format key:value?

hard🚀 Application Q9 of Q15
Python - File Handling Fundamentals
How can you write a dictionary data = {'a': 1, 'b': 2} to a file so that each key-value pair is on its own line in the format key:value?
Awith open('dict.txt', 'w') as f: for k, v in data.items(): f.write(f'{k}:{v}\n')
Bwith open('dict.txt', 'w') as f: f.write(str(data))
Cwith open('dict.txt', 'a') as f: f.write(data)
Dwith open('dict.txt', 'w') as f: f.write(data.items())
Step-by-Step Solution
Solution:
  1. Step 1: Iterate dictionary items

    Looping over data.items() gives key and value pairs.
  2. Step 2: Write formatted string per line

    Using f-string with '\n' writes each pair on its own line.
  3. Final Answer:

    Loop and write f'{k}:{v}\n' for each item. -> Option A
  4. Quick Check:

    Write dict lines with loop and f-string [OK]
Quick Trick: Loop dict items and write f'{k}:{v}\n' [OK]
Common Mistakes:
MISTAKES
  • Writing dict object directly
  • Using append mode incorrectly
  • Writing dict_items object

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes