Python

Python Fundamentals

Dictionaries

A dictionary (dict) stores data as key-value pairs — instead of looking items up by numeric position (like a list), you look them up by a key.

JrCodex·4 min read

Jr Codex Python Notes

Level: Beginner Prerequisites: Chapter 7 Time to complete: ~25 minutes


Table of Contents

  1. What is a Dictionary?
  2. Accessing & Modifying Values
  3. Common Dictionary Methods
  4. Iterating Over Dictionaries
  5. Nested Dictionaries
  6. Dictionary Comprehensions (Preview)
  7. What Can Be a Key?
  8. Summary & Next Steps

1. What is a Dictionary?

A dictionary (dict) stores data as key-value pairs — instead of looking items up by numeric position (like a list), you look them up by a key.

person = {
    "name": "Alice",
    "age": 25,
    "city": "Boston",
}
 
print(person["name"])     # "Alice"
print(len(person))          # 3 — number of key-value pairs
List vs Dict
─────────────────────────────────────────
  fruits = ["apple", "banana"]     ← position-based: fruits[0]
  ages = {"Alice": 25, "Bob": 30}  ← key-based: ages["Alice"]
─────────────────────────────────────────

Since Python 3.7, dictionaries preserve insertion order — a guarantee, not an implementation detail.


2. Accessing & Modifying Values

person = {"name": "Alice", "age": 25}
 
print(person["name"])         # "Alice"
print(person["email"])        # KeyError: 'email' — key doesn't exist!
 
# Safer access — .get() returns None (or a default) instead of raising
print(person.get("email"))              # None
print(person.get("email", "N/A"))       # "N/A"
 
# Adding / updating
person["age"] = 26                # update existing key
person["email"] = "a@example.com" # add new key
print(person)                       # {'name': 'Alice', 'age': 26, 'email': 'a@example.com'}
 
# Removing
del person["email"]
age = person.pop("age")             # removes 'age' AND returns its value

Rule of thumb: use [] when the key is guaranteed to exist; use .get() when it might not.


3. Common Dictionary Methods

person = {"name": "Alice", "age": 25, "city": "Boston"}
 
print(person.keys())        # dict_keys(['name', 'age', 'city'])
print(person.values())       # dict_values(['Alice', 25, 'Boston'])
print(person.items())         # dict_items([('name','Alice'), ('age',25), ('city','Boston')])
 
print("name" in person)        # True — checks KEYS by default
print("Alice" in person)        # False — NOT checking values
 
person.update({"age": 26, "job": "Engineer"})   # merge in another dict
print(person)
 
person.setdefault("country", "USA")  # only sets if key is missing
print(person["country"])               # "USA"
MethodPurpose
.get(key, default)Safe lookup, no KeyError
.keys() / .values() / .items()Views for iteration
.update(other_dict)Merge another dict in, overwriting shared keys
.pop(key)Remove key & return its value
.setdefault(key, default)Set a value only if the key is missing

4. Iterating Over Dictionaries

person = {"name": "Alice", "age": 25, "city": "Boston"}
 
# Iterating keys (default)
for key in person:
    print(key)
 
# Iterating key-value pairs — the most common pattern
for key, value in person.items():
    print(f"{key}: {value}")
 
# Iterating values only
for value in person.values():
    print(value)

5. Nested Dictionaries

Real-world data (API responses, config files, JSON — covered in Module 3) is almost always nested dicts and lists:

users = {
    "alice": {"age": 25, "roles": ["admin", "editor"]},
    "bob":   {"age": 30, "roles": ["viewer"]},
}
 
print(users["alice"]["age"])          # 25
print(users["alice"]["roles"][0])      # "admin"
 
for username, info in users.items():
    print(f"{username}: age={info['age']}, roles={info['roles']}")

6. Dictionary Comprehensions (Preview)

A quick preview — full comprehension syntax (list/dict/set) is covered in Module 2, Chapter 5. Dict comprehensions build a dictionary in one line:

squares = {n: n**2 for n in range(1, 6)}
print(squares)      # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
 
prices = {"apple": 1.0, "banana": 0.5, "cherry": 3.0}
discounted = {item: price * 0.9 for item, price in prices.items()}
print(discounted)     # {'apple': 0.9, 'banana': 0.45, 'cherry': 2.7}

7. What Can Be a Key?

Dictionary keys must be hashable (roughly: immutable) — this is the same hashability idea introduced with tuples in Chapter 7.

valid = {
    "name": "Alice",       # str ✓
    42: "answer",           # int ✓
    (1, 2): "point",         # tuple ✓ (immutable)
    True: "flag",              # bool ✓
}
 
invalid = {
    [1, 2]: "point"          # TypeError: unhashable type: 'list'
}
Valid Key TypesInvalid Key Types
str, int, float, bool, tuple (of hashables)list, dict, set (all mutable)

8. Summary & Next Steps

Key Takeaways

  • Dictionaries map keys → values and preserve insertion order (Python 3.7+).
  • .get(key, default) avoids KeyError for keys that might not exist — prefer it over [] for uncertain lookups.
  • .items() is the standard way to loop over both keys and values together.
  • Keys must be hashable — this is why tuples (not lists) can be dictionary keys.

Concept Check

  1. What's the difference between person["email"] and person.get("email") when "email" isn't a key?
  2. Why can't a list be used as a dictionary key?
  3. Given users = {"alice": {"age": 25}}, how do you access Alice's age?

Next Chapter

Chapter 9: Sets


Jr Codex — 1-on-1 Personalized Coaching | Back to Module Index