Dictionaries & Sets: Hash Tables and Uniqueness

Module 2 • Session 16 • Allocation: 1 Contact Hr

set hashmap O(1) search set algebra

Dictionaries and sets are high-performance container structures in Python implemented via underlying hash tables. Dictionaries map unique keys to values, whereas sets manage unordered collections of distinct elements. Both provide near-instantaneous $O(1)$ constant time lookup operations.

1. Structural Comparison: Dictionaries vs Sets

Understanding how hash-based structures differ from ordered sequences like lists or tuples allows you to structure application state efficiently.

Feature Dictionary (dict) Set (set)
Syntax Key-value mappings: {"key": "value"} Unique element list: {1, 2, 3}
Key / Element Requirement Keys must be hashable (immutable); values can be any type. All elements must be hashable (immutable) and unique.
Ordering Insertion-ordered (guaranteed since Python 3.7+). Unordered collection.
Primary Use Case Structured records, lookups, JSON data processing. Deduplication, membership testing, set mathematics.

2. Dictionary Methods & Operations

Dictionaries allow querying, updating, and iterating over key-value pairs safely using built-in helper methods.

# Initializing a dictionary user_profile = { "username": "alex99", "email": "alex@example.com", "role": "admin" } # Safe key retrieval with .get() (prevents KeyError) age = user_profile.get("age", 25) # Returns default 25 if key is missing # Updating & Adding entries user_profile["status"] = "active" user_profile.update({"role": "superadmin", "login_count": 12}) # Removing entries role = user_profile.pop("role") # Removes 'role' and returns value last_item = user_profile.popitem() # Removes and returns last inserted key-value pair # Iterating over dictionaries for key, value in user_profile.items(): print(f"{key}: {value}")
Safe Access Tip: Direct indexing like user_profile["missing_key"] raises a KeyError. Using user_profile.get("missing_key", default) guarantees safe key access without program halts.

3. Set Mathematics & Operations

Sets eliminate duplicates automatically and support native mathematical operators for set relationships.

# Initializing sets (Note: {} creates an empty dict; use set() for an empty set) frontend_devs = {"Alice", "Bob", "Charlie"} backend_devs = {"Charlie", "David", "Eve"} # Set Algebra Operations full_stack = frontend_devs | backend_devs # Union: All unique developers both_skills = frontend_devs & backend_devs # Intersection: Devs in both sets only_frontend = frontend_devs - backend_devs # Difference: Frontends not in backend exclusive_devs = frontend_devs ^ backend_devs # Symmetric Difference: In either, but not both print("Union:", full_stack) print("Intersection:", both_skills) print("Only Frontend:", only_frontend) # Deduplicating a list using set() raw_tags = ["python", "code", "python", "data", "code"] unique_tags = list(set(raw_tags)) print("Deduplicated List:", unique_tags)
Empty Set Gotcha: Writing empty_var = {} creates an empty dictionary. To initialize an empty set, you must write empty_set = set().

4. Time Complexity & Hashability

Hash tables assign an integer hash value to each stored key/element using Python's internal hash() function. This conversion enables instant address calculation.

# Checking hashability print(hash("hello")) # Works (String is immutable) print(hash((1, 2, 3))) # Works (Tuple of immutables is hashable) # Attempting to hash a mutable type raises TypeError: try: hash([1, 2, 3]) # Lists are mutable! except TypeError as e: print("Hash Error:", e)

🏋️ Try It Yourself: Practice Challenges

Challenge 1: Word Frequency Counter

Write a script that accepts a text string and uses a dictionary to compute and output the word count frequency for each unique word.

Challenge 2: Common Interest Finder

Given two lists of user interest tags, use set operations to find and output the interests shared by both users as well as the interests unique to the first user.

Challenge 3: Inverted Key-Value Mapper

Write a function that takes a dictionary and returns a new dictionary where the original keys become values and original values become keys.

⚡ Interactive Sandbox (Dictionary & Set Playground)
Console Output:
Click "Run Code" above to execute interactive dictionary and set scripts...

📝 Knowledge Check Quiz

1. What happens when you execute `my_dict["nonexistent_key"]` directly?
2. How do you create an empty set in Python?
3. Which of the following data types CANNOT be used as a dictionary key or set element?
Advertisement
Horizontal Ad Banner Slot (728x90 / Responsive)