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

A developer is debugging a Python script that interacts with a REST API. The script frequently encounters 'KeyError' exceptions when trying to access values from a dictionary returned by the API, even though the keys seem to exist in successful responses. They want to ensure the script handles cases where a key might be missing gracefully without crashing. Which Python dictionary method provides a safe way to retrieve a value, returning a default if the key is not found?

  1. Adict.find()
  2. Bdict.has_key()
  3. Cdict.get()
  4. Ddict.lookup()
Show answer & explanation

Correct answer: C. dict.get()

The `dict.get()` method attempts to retrieve a value associated with a given key. If the key is not found, it returns `None` by default or a specified default value, preventing a `KeyError` and allowing for graceful error handling.

Why the other options are wrong

  • A. `find()` is not a standard dictionary method in Python.
  • B. `has_key()` was removed in Python 3. The correct way to check for a key's existence is `key in dict`.
  • D. `lookup()` is not a standard dictionary method in Python.

Python dict.get()

The `get()` method for Python dictionaries returns the value for the specified key if the key is in the dictionary. If the key is not found, it returns a specified default value (or `None` if no default is provided) instead of raising a `KeyError`.

  • Syntax: `dictionary.get(key, default_value=None)`.
  • Useful for preventing `KeyError` exceptions when accessing potentially missing keys.
  • Increases the robustness and error handling of Python scripts.

Memory trick: Get keys safely, or get a default.

More Software Development and Design questions