DevNet Associate (DEVASC) v1.0Software Development and DesignMedium
A network automation script needs to store a collection of key-value pairs where the keys are unique device serial numbers (strings) and the values are complex objects representing device configurations. It's crucial to retrieve a device's configuration quickly by its serial number. Which Python data structure offers the most efficient lookup by key?
- ASet of strings
- BDictionary
- CList of tuples
- DList of dictionaries
Show answer & explanationAnswer & explanation
Correct answer: B. Dictionary
A Python dictionary is optimized for efficient key-value storage and retrieval. It provides average O(1) (constant time) complexity for lookup operations, making it ideal for quickly accessing device configurations by their unique serial numbers.
Why the other options are wrong
- A. A set stores unique items but not key-value pairs; it's used for efficient membership testing, not for storing associated values.
- C. A list of tuples would require iterating through the list to find a matching serial number, resulting in O(n) lookup time.
- D. A list of dictionaries would also require iterating through the list, checking a key in each dictionary, resulting in O(n) lookup time.
Python Dictionary
A Python dictionary is an unordered collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, holds key:value pair. Keys must be unique and immutable.
- Stores key-value pairs
- Keys must be unique and immutable
- Values can be of any data type
- Highly efficient for key-based lookups (average O(1) time complexity)
Memory trick: Dictionaries are like fast indexes, finding keys instantly.