Dictionaries - Your Personal Information Organizer
A dictionary is like a contact list on your phone. Each person (key) has associated information (value): name, phone number, email. Instead of remembering positions like in a list, you remember the person's name to get their details.
A **dictionary** is a collection of key‑value pairs. Unlike lists, which are indexed by position (0, 1, 2…), dictionaries use **keys** to look up **values**. This makes them perfect for storing structured data where each piece of information has a meaningful label.
**Creating a dictionary:**
Use curly braces `{}` with key‑value pairs separated by commas. Keys and values are separated by a colon `:`.
```python
student = {
"name": "Alex",
"age": 20,
"major": "Computer Science"
}
```
Keys are usually strings or numbers; values can be any data type (strings, numbers, lists, even other dictionaries).
**Accessing values:**
Use square brackets with the key:
```python
print(student["name"]) # Alex
```
If the key doesn't exist, Python raises a `KeyError`. To avoid that, use the `.get()` method, which returns `None` (or a default) instead of crashing:
```python
print(student.get("grade")) # None
print(student.get("grade", "N/A")) # N/A
```
**Adding and modifying items:**
Assign a value to a key. If the key already exists, the value is updated; if it's new, the key‑value pair is added:
```python
student["year"] = "Sophomore" # add new key-value
student["age"] = 21 # update existing key
```
**Removing items:**
- `del dict[key]` – removes the key‑value pair.
- `.pop(key)` – removes and returns the value.
- `.popitem()` – removes and returns the last inserted key‑value pair (Python 3.7+).
- `.clear()` – removes all items.
**Checking existence:**
Use the `in` operator to test if a key exists:
```python
if "major" in student:
print(student["major"])
```
**Dictionary methods:**
- `.keys()` – returns a view of all keys.
- `.values()` – returns a view of all values.
- `.items()` – returns a view of (key, value) pairs as tuples.
**Looping through a dictionary:**
```python
# loop over keys
for key in student:
print(key, student[key])
# loop over items
for key, value in student.items():
print(f"{key}: {value}")
```
**Dictionary comprehensions (advanced but useful):**
```python
squares = {x: x**2 for x in range(5)} # {0:0, 1:1, 2:4, 3:9, 4:16}
```
**Important properties:**
- Keys must be **immutable** (strings, numbers, tuples) – lists and other dictionaries cannot be keys.
- Values can be **any** data type.
- From Python 3.7 onward, dictionaries **preserve insertion order**.
- Dictionaries are **mutable** – you can change, add, or remove items.
**When to use dictionaries vs. lists:**
- Use a **list** for ordered sequences where you access by position (e.g., a list of tasks).
- Use a **dictionary** for labeled data where you need fast lookup by a unique key (e.g., a user profile, configuration settings).
**Common mistakes:**
- Using a list as a key – raises `TypeError`.
- Forgetting that `.keys()`, `.values()`, `.items()` return views, not lists (convert with `list()` if needed).
- Assuming dictionaries are ordered in older Python versions (< 3.7).
- Using `=` instead of `==` when checking for key existence.
**Real‑world applications:**
- Storing user profiles (name, email, preferences).
- Counting frequencies (e.g., word counts in a text).
- Caching results of expensive function calls (memoization).
- Representing JSON data from APIs.
- Configuration settings (`config = {"theme": "dark", "language": "en"}`).
**Practice exercises:**
1. Create a dictionary for a book: title, author, year, genre. Print each key and value.
2. Add a new key `"pages"` and update the year. Remove the genre key.
3. Write a function that takes a dictionary and a key, and returns the value if the key exists, otherwise returns `"Not found"` (use `.get()`).
4. Given a list of words, count how many times each word appears using a dictionary.
5. Merge two dictionaries (e.g., `d1 = {"a": 1, "b": 2}`, `d2 = {"c": 3, "d": 4}`) into one.
**Example using `.pop()` and `.get()`:**
```python
value = my_dict.pop("key", default) # removes and returns, or default if not found
```
# ========== EXAMPLE 1: Creating, Accessing, and Modifying Dictionaries ==========
print("=== Example 1: Student Profile ===")
student = {
"name": "Alex",
"age": 20,
"major": "Computer Science",
"gpa": 3.8
}
print(f"Original student: {student}")
# Accessing values
print(f"\nName: {student['name']}")
print(f"Age: {student['age']}")
# Adding a new key-value pair
student["year"] = "Sophomore"
print(f"\nAfter adding 'year': {student}")
# Modifying an existing value
student["gpa"] = 3.9
print(f"After updating GPA: {student}")
print()
# ========== EXAMPLE 2: Key Existence, .get(), and Safe Access ==========
print("=== Example 2: Safe Access and Key Checking ===")
# Check if key exists
if "major" in student:
print(f"Major: {student['major']}")
else:
print("Major not found")
# Using .get() to avoid KeyError
print(f"Grade (using get): {student.get('grade', 'Not assigned')}")
print(f"Name (using get): {student.get('name')}")
# Removing an item with .pop()
removed = student.pop("year")
print(f"\nRemoved 'year': {removed}")
print(f"After pop: {student}")
print()
# ========== EXAMPLE 3: Looping, keys(), values(), items() ==========
print("=== Example 3: Looping Through Dictionaries ===")
print("All keys:", list(student.keys()))
print("All values:", list(student.values()))
print("\nStudent details (using .items()):")
for key, value in student.items():
print(f"{key}: {value}")
# Phone book example (real-world usage)
print("\n--- Phone Book Directory ---")
contacts = {
"Alice": "555-1234",
"Bob": "555-5678",
"Charlie": "555-9012"
}
for name, number in contacts.items():
print(f"{name}: {number}")
# Safe lookup
def find_contact(phone_book, name):
return phone_book.get(name, "Contact not found")
print(f"\nAlice's number: {find_contact(contacts, 'Alice')}")
print(f"David's number: {find_contact(contacts, 'David')}")
→ Run this code interactively