Dicts map hashable keys to values—like JavaScript objects or Java HashMap. Sets hold unique unordered elements—great for membership tests and deduplication.
Dict operations
user = {"name": "Ada", "role": "dev"}
user["email"] = "ada@example.com"
print(user.get("missing", "N/A"))
for key, value in user.items():
print(key, value)
Sets
tags = {"python", "web", "python"}
print(tags) # {'python', 'web'}
print("python" in tags)
Keys must be hashable—lists cannot be keys; tuples can if elements are hashable.
Important interview questions and answers
- Q: dict[key] vs get?
A:dict[key]raisesKeyErrorif missing;getreturnsNoneor a default. - Q: Set vs list for uniqueness?
A: Sets enforce uniqueness and O(1) average membership; lists allow duplicates and preserve order.
Self-check
- How iterate key-value pairs in a dict?
- Can a list be a dict key?
Pitfall: d[key] raises KeyError—use .get() when missing keys are expected.
Interview prep
- dict vs list lookup?
Dict average O(1) key lookup; list scan is O(n)—pick dict for keyed access.
- Set use case?
Unique membership tests and deduplication—unordered collection of hashable items.