300-435 Question 22
Single answerYou are debugging a Python script designed to analyze network devices' status from a JSON file and display the devices that are currently 'online'. However, the script is failing to display the correct output. Analyze the following Python script snippet and identify the issue:
def filter_online_devices(devices):
online_devices = []
for device in devices:
if device['status'] == 'online':
online_devices.append(device['name'])
return online_devices
# JSON data input
network_devices = [
{"name": "Router1", "status": "online"},
{"name": "Switch1", "status": "offline"},
{"name": "Firewall1", "status": "online"}
]
# Function call
result = filter_online_devices(network_devices)
print(result)
- A
The script does not handle cases where the 'status' key is missing in a device dictionary.
- B
The loop incorrectly compares the status value, as it should use 'ONLINE' instead of 'online'.
- C
The function is correctly implemented and should output a list of device names that are online.
- D
The script fails because the input JSON data format is invalid.
Show answer and explanation
Correct answer: C
Explanation
The script is functioning as designed. It filters devices with a 'status' of 'online' and appends their names to a list. The JSON input data is valid, and the case comparison for 'online' matches the data. The output will correctly display ['Router1', 'Firewall1'].
- A. Incorrect.
This is not correct because the 'status' key exists in all device dictionaries in the provided JSON data. The script does not encounter a missing key issue in this specific scenario.
- B. Incorrect.
This is incorrect because the script correctly compares the 'status' value as 'online', which matches the case used in the JSON input.
- C. Correct.
This is correct because the script correctly iterates over the devices, checks their 'status', and appends the names of devices with 'online' status to the list. The output will be ['Router1', 'Firewall1'].
- D. Incorrect.
This is incorrect because the input JSON data is valid Python dictionary syntax and does not cause any errors.