Data Structures: Maps and Dictionaries Notes

Overview of Maps and Key Characteristics

  • General Definition: A map is a searchable collection of items stored as key-value pairs.

  • Key Constraints: Multiple items sharing the same key are not permitted; keys must be unique within the collection.

  • Primary Operations: The functionality of a map centers on three main actions:

    • Searching for items.

    • Inserting new items.

    • Deleting existing items.

  • Real-World Applications:

    • Social Media: Mapping a unique username to a complex object containing user information.

    • Student Databases: Mapping a student identification number (st#) to specific student record details.

    • Domain Name System (DNS): Mapping an IP address to its corresponding host name.

    • Color Systems: Mapping a specific color name (e.g., "blue") to its RGB (Red, Green, Blue) numerical representation.

Python Dictionaries vs. General Map ADTs

  • Python's dict Class: This is considered arguably the most significant data structure within the Python language.

  • Dictionary Abstraction: It represents a specific implementation of the dictionary abstraction where unique keys map to associated values.

  • Terminology Distinctions:

    • Dictionary: Used specifically when discussing Python’s internal dict class.

    • Map: Used when discussing the more general notion of the Abstract Data Type (ADT).

  • Implementation Detail: Python's dict class utilizes hashing. While highly efficient, the use of hashing can limit the number of specific applications (relative to potential variations of the Map ADT).

The Map Abstract Data Type (ADT) Behaviors

  • Core Behaviors: The Map ADT mimics the behavior of the Python dict class, specifically supporting 5 fundamental behaviors that allow for adding, deleting, modifying, and querying entries.

  • Extended Map Operations:

    • M.popitem(): Removes an arbitrary key-value pair from the map and returns it as a (k,v)(k, v) tuple. If the map is empty, it raises a KeyError.

    • M.clear(): Completely removes all key-value pairs from the map.

    • M.keys(): Provides a set-like view of all keys currently in the map.

    • M.values(): Provides a set-like view of all values currently in the map.

    • M.items(): Provides a set-like view of (k,v)(k, v) tuples representing all entries in the map.

    • M.update(M2): Performs a batch update where for every (k,v)(k, v) pair in map M2, it assigns M[k] = v in map M.

    • M == M2: Returns True if maps M and M2 contain identical key-value associations.

    • M != M2: Returns True if maps M and M2 do not have identical key-value associations.

Functional Trace Example

Starting with an empty map M = {}:

  • len(M): Returns 00. Map: { }.

  • M['K'] = 2: Initial insertion. Map: {'K': 2}.

  • M['B'] = 4: Insertion. Map: {'K': 2, 'B': 4}.

  • M['U'] = 2: Insertion (note: values can be duplicates, keys cannot). Map: {'K': 2, 'B': 4, 'U': 2}.

  • M['V'] = 8: Insertion. Map: {'K': 2, 'B': 4, 'U': 2, 'V': 8}.

  • M['K'] = 9: Updating existing key. Map: {'K': 9, 'B': 4, 'U': 2, 'V': 8}.

  • M['B']: Query returns 44.

  • M['X']: Query fails; raises KeyError.

  • M.get('F'): Returns None (default for missing key).

  • M.get('F', 5): Returns the provided default value 55.

  • M.get('K', 5): Returns the actual value 99.

  • len(M): Returns current size 44.

  • del M['V']: Deletion. Map: {'K': 9, 'B': 4, 'U': 2}.

  • M.pop('K'): Removes key 'K' and returns value 99.

  • M.keys(): Returns view containing 'B', 'U'.

  • M.values(): Returns view containing 4,24, 2.

  • M.items(): Returns view containing ('B', 4), ('U', 2).

  • M.setdefault('B', 1): Key 'B' exists, returns existing value 44.

  • M.setdefault('A', 1): Key 'A' does not exist; inserts {'A': 1} and returns 11. Map: {'A': 1, 'B': 4, 'U': 2}.

  • M.popitem(): Removes an arbitrary pair, e.g., ('B', 4). Remaining map: {'A': 1, 'U': 2}.

Implementation via Unsorted List

  • General Structure: A simple implementation uses an unsorted list S (often based on a doubly-linked list) to store items in arbitrary order. Items are represented as specific key-value pair nodes between a header and trailer sentinel.

  • The MapBase Abstract Class: A base class used to provide basic structure, including a nested _Item class.

    • Class _Item: A lightweight composite used to store the key-value pairs.

    • Slots: Uses __slots__ = '_key', '_value' to optimize memory usage by preventing the creation of instance dictionaries.

  • The MyMap Class Implementation:

    • Constructor: Initializes self._table = [], which is a list of _Item objects.

    • __getitem__(self, k): Maps to the standard operation M[k]. It iterates through every item in self._table. If item._key == k, it returns item._value. If the loop completes without a match, it raises KeyError.

    • __setitem__(self, k, v): Maps to M[k] = v. It iterates through the list. If it finds a matching key, it reassigns the value (item._value = v) and exits. If no match is found, it appends a new _Item(k, v) to the list.

    • __delitem__(self, k): Maps to del M[k]. It iterates by index through range(len(self._table)). When a match is found, it uses self._table.pop(j) to remove the item and exits. If no match is found, it raises KeyError.

    • __len__(self): Returns the result of len(self._table).

Performance Analysis of List-Based Maps

  • Time Complexity:

    • Searching: O(n)O(n). In the worst case (item not found), the entire list must be traversed.

    • Removing: O(n)O(n). Requires searching for the item first.

    • Inserting/Updating: O(n)O(n). Since keys must be unique, the implementation must first traverse the entire list to ensure the key does not already exist before performing an update or an append.

  • Practical Use Cases:

    • Effective only for very small maps.

    • Useful in scenarios where insertions are frequent but searches and removals are extremely rare (e.g., maintaining a historical record of logins on a workstation).