## Dictionary: Key-Value Storage
A dictionary is like a real-life dictionary where you look up a word (key) to find its definition (value).
**Characteristics:**
- Stores data as **key-value pairs**
- Keys **must be unique** (like dictionary headwords)
- Values can be any data type
- Ordered (maintains insertion order since Python 3.7)
- Mutable (can change after creation)
```python
# Creating a dictionary
phonebook = {
"Alice": "555-1234",
"Bob": "555-5678",
"Charlie": "555-9012"
}
# Accessing values
print(phonebook["Alice"]) # Output: "555-1234"
# Adding new entry
phonebook["David"] = "555-3456"
# Removing entry
del phonebook["Bob"]
```
### Common Dictionary Methods:
- `.keys()` - returns all keys
- `.values()` - returns all values
- `.items()` - returns key-value pairs
- `.get(key)` - safer way to access values
- `.update()` - merge dictionaries
## 🧮 Set: Unique Element Container
A set is like a mathematical set or a bag of unique items - it automatically removes duplicates.
**Characteristics:**
- Contains only **unique elements**
- Unordered (no index positions)
- Mutable (can add/remove items)
- Extremely fast membership tests
```python
# Creating a set
fruits = {"apple", "banana", "orange", "apple"}
print(fruits) # Output: {'apple', 'banana', 'orange'} (duplicate removed)
# Adding elements
fruits.add("grape")
# Removing elements
fruits.discard("banana")
# Membership test
print("apple" in fruits) # True
```
### Common Set Operations:
- Union (`|`) - combines sets
- Intersection (`&`) - common elements
- Difference (`-`) - elements in first not in second
- Symmetric Difference (`^`) - elements in either but not both
## Key Differences
| Feature | Dictionary | Set |
|--------------|------------|-----|
| Purpose | Map keys to values | Store unique elements |
| Syntax | `{key: value}` | `{element}` |
| Order | Ordered | Unordered |
| Duplicates | Unique keys only | All elements unique |
| Lookup | By key | By value existence |
| Performance | O(1) key access | O(1) membership test |
**Use Dictionary when** you need to associate values with unique identifiers (like a database record).
**Use Set when** you need to ensure uniqueness or perform set math operations.