Bird
0
0

You want to save a Python dictionary {'a': 1, 'b': 2, 'c': 3} to a JSON file and then read it back. Which code snippet correctly does this and prints the value of key 'b'?

hard📝 Application Q15 of 15
Python - Structured Data Files

You want to save a Python dictionary {'a': 1, 'b': 2, 'c': 3} to a JSON file and then read it back. Which code snippet correctly does this and prints the value of key 'b'?

A<pre>import json with open('file.json', 'w') as f: json.dump({'a': 1, 'b': 2, 'c': 3}, f) with open('file.json', 'r') as f: data = json.load(f) print(data['b'])</pre>
B<pre>import json with open('file.json', 'r') as f: json.dump({'a': 1, 'b': 2, 'c': 3}, f) with open('file.json', 'w') as f: data = json.load(f) print(data['b'])</pre>
C<pre>import json f = open('file.json', 'w') json.load({'a': 1, 'b': 2, 'c': 3}, f) f.close() f = open('file.json', 'r') data = json.dump(f) f.close() print(data['b'])</pre>
D<pre>import json with open('file.json', 'w') as f: json.load({'a': 1, 'b': 2, 'c': 3}, f) with open('file.json', 'r') as f: data = json.dump(f) print(data['b'])</pre>
Step-by-Step Solution
Solution:
  1. Step 1: Write dictionary to JSON file correctly

    json.dump writes Python dict to file opened in 'w' mode.
    import json
    with open('file.json', 'w') as f:
        json.dump({'a': 1, 'b': 2, 'c': 3}, f)
    with open('file.json', 'r') as f:
        data = json.load(f)
    print(data['b'])
    does this correctly.
  2. Step 2: Read JSON file and access key 'b'

    json.load reads JSON back from file opened in 'r' mode, then data['b'] prints 2.
  3. Final Answer:

    Code in Option A correctly saves and reads JSON, printing 2 -> Option A
  4. Quick Check:

    json.dump to write, json.load to read [OK]
Quick Trick: Use json.dump to write, json.load to read JSON files [OK]
Common Mistakes:
  • Using json.load to write data
  • Using json.dump to read data
  • Opening files in wrong modes

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes