A dictionary stores key-value pairs. Keys must be unique and immutable (strings, numbers, tuples). Values can be anything.
A set is an unordered collection of unique items. Duplicates are automatically removed.
When to use what: List for ordered data you'll iterate. Dict for labeled data (key-value). Set for fast membership tests or eliminating duplicates. Tuple for fixed, immutable data.
text = "the cat sat on the mat the cat"words = text.split() gives a list of words.freq.get(word, 0) returns the current count or 0 if the word isn't in the dict yet.{"the": 3, "cat": 2, "sat": 1, "on": 1, "mat": 1}max(freq, key=freq.get) returns "the".Create a dict mapping names to phone numbers. Write code to look up a name and print the number, or "Not found" if the name isn't in the book.
.get(key, default) is safer than [key] because it returns the default instead of raising KeyError when the key doesn't exist.Given two lists, find all elements that appear in both. Use sets for O(1) lookup.
What does d.get('key', 'default') do if 'key' is not in d?
d['key'] raises KeyError for missing keys. d.get('key', 'default') safely returns the default value instead.
d.get(key) with no default returns None. d.get(key, 'default') returns 'default' when key is missing.
.get() is read-only. To create a key with a default if missing, use d.setdefault('key', 'default').
Why are sets faster than lists for membership testing (x in s)?
Sets are unordered. Their speed comes from hashing, not sorting.
A set may use more memory than a list due to hash table overhead. The advantage is O(1) lookup time.
Speed comes from the data structure (hash table), not compilation. List search is O(n); set search is O(1).
What does {1, 2, 3} & {2, 3, 4} return?
| is union (all elements from both). & is intersection (only shared elements). {1,2,3} & {2,3,4} = {2,3}.
^ gives elements in one set or the other but not both. & gives elements in both sets.
{} would mean no common elements. But 2 and 3 appear in both sets, so intersection = {2,3}.
Which collection maintains insertion order and allows duplicates?
Sets: unordered, unique elements, O(1) lookup. Lists: ordered, allow duplicates.
Dict keys are unique, but values can repeat. Lists allow duplicate elements.
Tuples do maintain order and allow duplicates, but they're immutable. Lists are the mutable ordered sequence.
What is the output of len({1, 1, 2, 2, 3})?
The set {1,1,2,2,3} stores only unique values: {1,2,3}. len({1,2,3}) = 3.
The set ends up with 3 unique elements: 1, 2, 3. len = 3.
Sets of integers are valid. The set literal removes duplicates automatically. len returns 3.