Dictionaries and Sets in Python: Storing and Managing Unique Data
Python offers several ways to organize data. Two very useful built-in types are dictionaries and sets. They help you store data with fast access and enforce uniqueness where needed.
Let’s dive into what they are, how they work, and when to use them.
Dictionaries: Key-Value Stores
A dictionary stores data in key-value pairs — like a real dictionary where you look up a word (key) to get its meaning (value).
-
Keys must be unique and immutable (strings, numbers, tuples).
-
Values can be any data type.
-
Defined using curly braces
{}with colon:separating keys and values.
Creating a Dictionary
Accessing and Modifying
Useful Methods
-
.get(key, default)— safely get a value, returnsdefaultif key not found -
.keys(),.values(),.items()— iterate over keys, values, or key-value pairs -
.pop(key)— remove key and return its value
Sets: Unordered Collections of Unique Items
A set stores unique elements — no duplicates allowed. Great for membership tests and operations like unions and intersections.
-
Defined using curly braces
{}or theset()function. -
Elements must be immutable and unique.
-
No indexing because sets are unordered.
Creating a Set
Adding and Removing Elements
Set Operations
-
Union: Combine all elements
-
Intersection: Elements common to both sets
-
Difference: Elements in one set but not the other
-
Symmetric Difference: Elements in either set but not both
️ When to Use Which?
| Structure | Use Case |
|---|---|
| Dictionary | When you need key-based lookup (e.g., user data) |
| Set | When you need unique items or perform set math |
Summary
| Feature | Dictionary | Set |
|---|---|---|
| Syntax | {"key": "value"} |
{"apple", "banana"} |
| Order | Ordered (Python 3.7+) | Unordered |
| Mutability | Mutable | Mutable |
| Duplicate keys/items | No duplicate keys allowed | No duplicate items allowed |
| Access | By key | Membership testing |
