Dictionaries & Sets
Dictionaries — Key-Value Pairs
A dictionary is like a contact list on your phone. You look up a person's name (the key) and get their phone number (the value). You don't search by position — you search by name. That's what makes dictionaries lightning-fast for lookups — they use a hash function behind the scenes.
Dictionaries are created with curly braces {} and use key: value pairs separated by commas. Keys must be unique and immutable (strings, numbers, or tuples). Values can be anything.
Creating & Using Dictionaries
CRUD — Create, Read, Update, Delete
Dictionaries are mutable, so you can add, update, and remove entries freely. Here's how to do all four operations:
Modifying Dictionaries
Looping Through Dictionaries
Dictionaries give you three ways to iterate: over keys, values, or both (items). The .items() method is the most common — it gives you tuples of (key, value) that you can unpack right in the loop.
Iterating & Useful Patterns
Sets — Unique Items Only
A set is like a bag of unique marbles — you can't have duplicates, and there's no specific order. Sets are fantastic for removing duplicates, testing membership, and doing math-like operations (union, intersection, difference).
Sets & Set Operations
x in my_set is blazing fast (constant time), while x in my_list gets slower as the list grows. If you're checking membership frequently, convert your list to a set first!Quick check
Continue reading