Bird
Raised Fist0

Given a JSON string representing a list of dictionaries, how can you deserialize it and extract the value of key 'id' from the first dictionary?

hard🚀 Application Q9 of Q15
Python - Structured Data Files
Given a JSON string representing a list of dictionaries, how can you deserialize it and extract the value of key 'id' from the first dictionary?
json_str = '[{"id": 101, "name": "A"}, {"id": 102, "name": "B"}]'
Apy_list = json.dumps(json_str); print(py_list[0]['id'])
Bpy_list = json.loads(json_str); print(py_list[0]['id'])
Cpy_list = json.load(json_str); print(py_list['id'])
Dpy_list = json.loads(json_str); print(py_list['id'])
Step-by-Step Solution
Solution:
  1. Step 1: Deserialize JSON string to Python list

    Use json.loads(json_str) to convert the JSON string into a Python list of dictionaries.
  2. Step 2: Access first dictionary and get 'id'

    Access the first element with py_list[0] and then get the 'id' value with ['id'].
  3. Final Answer:

    py_list = json.loads(json_str); print(py_list[0]['id']) -> Option B
  4. Quick Check:

    loads() to list, index then key access [OK]
Quick Trick: loads() returns list; index then key for value [OK]
Common Mistakes:
MISTAKES
  • Using dumps() instead of loads()
  • Trying to access key on list directly
  • Using load() without file

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes