200-901 Question 8
Select 2You are developing a Python application to interact with a REST API that returns JSON data. The API response contains nested structures, including lists and dictionaries. Your task is to extract the 'device_name' from the following JSON response:
{ "devices": [ {"id": 1, "device_name": "Router1", "status": "active"}, {"id": 2, "device_name": "Switch1", "status": "inactive"} ] }
Which of the following Python code snippets correctly extracts the device names into a list?
- A
[device['device_name'] for device in response['devices']]
- B
[response['device_name'] for device in response['devices']]
- C
list(map(lambda x: x['device_name'], response['devices']))
- D
response['devices']['device_name']
- E
response.devices['device_name']
Show answer and explanation
Correct answers: A, C
Explanation
In the given JSON structure, 'device_name' is a key within dictionaries that are elements of the 'devices' list. To extract the device names, you need to iterate over the list and access the 'device_name' key in each dictionary. Both the list comprehension and the map function are valid ways to achieve this.
- A. Correct.
This is the correct way to use a list comprehension to access the 'device_name' key in each dictionary within the 'devices' list.
- B. Incorrect.
This is incorrect because 'response' does not have a direct 'device_name' key; it is nested within the 'devices' list.
- C. Correct.
This is another correct approach using the map function to extract 'device_name' from each dictionary in the 'devices' list.
- D. Incorrect.
This is incorrect because 'response['devices']' is a list, and you cannot directly access 'device_name' without iterating over the list.
- E. Incorrect.
This is invalid Python syntax, as 'response' is a dictionary and does not support dot notation for key access.