Bird
Raised Fist0

You have a list of dictionaries representing users:

hard🚀 Application Q15 of Q15
Python - Structured Data Files
You have a list of dictionaries representing users:
users = [{'name': 'Bob', 'age': 25}, {'name': 'Eve', 'age': 28}]

How do you create a JSON string with indentation of 2 spaces and keys sorted alphabetically?
Ajson.dumps(users, indent='2', sort_keys=True)
Bjson.dumps(users, indent=2, sort=True)
Cjson.dumps(users, indent=2, sort_keys=True)
Djson.dumps(users, pretty=2, sort_keys=True)
Step-by-Step Solution
Solution:
  1. Step 1: Use json.dumps with indent and sort_keys

    The indent parameter formats the JSON with spaces and new lines. The sort_keys=True sorts dictionary keys alphabetically.
  2. Step 2: Validate correct parameter names and types

    json.dumps(users, indent=2, sort_keys=True) uses correct parameters and types. json.dumps(users, indent=2, sort=True) uses invalid parameter sort. json.dumps(users, indent='2', sort_keys=True) passes indent as string which is invalid. json.dumps(users, pretty=2, sort_keys=True) uses invalid parameter pretty.
  3. Final Answer:

    json.dumps(users, indent=2, sort_keys=True) -> Option C
  4. Quick Check:

    Use indent=int and sort_keys=True [OK]
Quick Trick: Use sort_keys=True and indent as integer [OK]
Common Mistakes:
MISTAKES
  • Using wrong parameter names like sort or pretty
  • Passing indent as string
  • Forgetting sort_keys to sort keys

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes