Bird
0
0

Given a list of dictionaries:

hard📝 Application Q9 of 15
Python - Structured Data Files
Given a list of dictionaries:
data = [{'id': 3, 'value': 10}, {'id': 1, 'value': 20}, {'id': 2, 'value': 15}]

Which code snippet formats this list as JSON sorted by the 'id' key inside each dictionary?
Ajson.dumps(sorted(data, key=lambda x: x['id']), indent=2)
Bjson.dumps(data, sort_keys=True, indent=2)
Cjson.dumps(data.sort(key=lambda x: x['id']), indent=2)
Djson.dumps(data, indent=2)
Step-by-Step Solution
Solution:
  1. Step 1: Sort the list by 'id'

    Use sorted(data, key=lambda x: x['id']) to sort the list of dictionaries by the 'id' key.
  2. Step 2: Format sorted list as JSON with indentation

    Pass the sorted list to json.dumps() with indent=2 for pretty printing.
  3. Final Answer:

    json.dumps(sorted(data, key=lambda x: x['id']), indent=2) -> Option A
  4. Quick Check:

    Sort list first, then dump JSON with indent [OK]
Quick Trick: Sort list before json.dumps to order items [OK]
Common Mistakes:
  • Using sort_keys to sort list items (only sorts dict keys)
  • Calling list.sort() inside json.dumps (returns None)
  • Not sorting list before dumping

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes