← Back to libraryQuestion 191 of 468
🐍PythonBeginner

Dictionaries

πŸ“Œ Definition:

A dictionary is a mutable mapping of unique keys to values with average O(1) lookup, insertion, and deletion. It's the workhorse for structured test data and JSON-like payloads.

πŸ“– Detailed Explanation:

You create dicts with {} or dict(), access with d[key] (KeyError if missing) or d.get(key, default) (safe), and iterate with .items(), .keys(), .values(). Dicts preserve insertion order (Python 3.7+). Useful patterns for testers: building request payloads, mapping ids to records, counting with dict.get or collections.Counter, and merging with {**a, **b} or a | b. Nested dicts model JSON responses directly, so parsing an API body and asserting response['data']['id'] == 5 is natural.

πŸ”‘ Key Points:
  • Keyβ†’value map with average O(1) operations
  • d.get(key, default) avoids KeyError; d[key] raises it
  • Insertion-ordered (3.7+); iterate with .items()
  • Models JSON payloads; merge with {**a, **b} or a | b
🌍 Real-World Example:

Building a POST body: payload = {'name': name, 'roles': ['qa'], 'active': True} then requests.post(url, json=payload) β€” the dict maps directly to JSON the API expects.

🎯 Scenario-Based Interview Question:

response['data']['token'] raises KeyError intermittently when the API omits 'data' on errors. How do you read it safely?