DevNet Associate (DEVASC) v1.0Software Development and DesignMedium

A Python script needs to parse a JSON response from a REST API. The response contains a list of network devices, and each device object has keys like 'hostname', 'ip_address', and 'status'. The script needs to extract the 'ip_address' of all devices where the 'status' is 'active'. Which Python code snippet correctly accomplishes this task assuming the JSON response is already loaded into a variable named `data`?

  1. Aactive_ips = [data[i]['ip_address'] for i in range(len(data)) if data[i]['status'] == 'active']
  2. Bactive_ips = [device['ip_address'] for device in data if device['status'] == 'active']
  3. Cactive_ips = [device.get('ip_address') for device in data if device.get('status') == 'active']
  4. Dactive_ips = [] for device in data: if device['status'] == 'active': active_ips.append(device['ip_address'])
Show answer & explanation

Correct answer: B. active_ips = [device['ip_address'] for device in data if device['status'] == 'active']

Option A uses a list comprehension, which is a concise and Pythonic way to create a new list by iterating over an existing one and applying a condition and transformation. This directly extracts the 'ip_address' for active devices.

Why the other options are wrong

  • A. While functionally correct, iterating using `range(len(data))` and indexing `data[i]` is less Pythonic and generally less readable than direct iteration over elements (`for device in data`).
  • C. Using `.get()` is good practice for dictionary lookups to avoid `KeyError` if a key might be missing. However, the problem implies the keys exist. The primary issue here is that the question asks for the 'ip_address' of *all* active devices, and this syntax is correct for that, but A is more common. However, the use of `device.get('ip_address')` could return `None` which might not be desired if 'ip_address' is guaranteed to exist. Given the problem implies existence, `device['ip_address']` is standard. The provided solution in A is more direct.
  • D. This code snippet is functionally correct and achieves the goal. However, list comprehensions (Option A) are generally considered more concise and Pythonic for this type of operation.

Python List Comprehension

List comprehensions provide a concise way to create lists. It consists of brackets containing an expression followed by a `for` clause, then zero or more `for` or `if` clauses. The result is a new list resulting from evaluating the expression in the context of the `for` and `if` clauses which follow it.

  • Concise syntax for list creation
  • More readable than traditional loops for simple cases
  • Can include conditional filtering (`if` clause)
  • Can include nested loops

Memory trick: List comprehensions build new lists, filtering and transforming as they go.

More Software Development and Design questions