← Previous

Lesson 13

Dictionaries and key-value data

~35 min

1. What is a Dictionary?

A dictionary (dict) is an unordered, mutable collection of elements stored as **key-value pairs**. Unlike lists where elements are accessed via their numerical index position, dictionary values are mapped directly to unique **keys**. Dictionaries are highly efficient for lookup operations, representing records, and structuring complex database outputs.

2. Key Constraints and Accessing Values

Dictionary keys must be of an **immutable (hashable)** data type, such as strings, integers, or tuples. Lists and other dictionaries are mutable and cannot be used as keys. Values, however, can be of any data type, including duplicates and nested collections.

If you try to access a non-existent key using bracket notation (dict[key]), Python will crash with a KeyError. To access keys safely without crashing, use the .get(key, default) method, which returns a default value (or None) if the key isn't found.

user = {
    "name": "Riya",
    "email": "riya@example.com",
    "score": 95
}

# Standard Access (crashes if key not found)
print(user["name"])  # Prints: Riya

# Safe Access
phone = user.get("phone", "No phone registered")
print(phone)  # Prints: No phone registered

3. Updating and Traversing Dictionaries

You can add or update key-value pairs using assignment, or loop over them. By default, iterating over a dictionary loops over its **keys**. To loop over both keys and values, use the .items() method, which returns them as tuple pairs.

user["score"] = 98            # Updates existing key
user["location"] = "Mumbai"   # Adds new key-value pair

# Iterate through keys and values
for key, val in user.items():
    print(f"{key} is set to: {val}")

4. Nested Dictionaries

Dictionaries can store other dictionaries as values. This is perfect for managing structured relational data, like databases or catalog systems.

students = {
    "student_01": {"name": "Aman", "grade": "A"},
    "student_02": {"name": "John", "grade": "B"}
}
print(students["student_01"]["name"])  # Prints: Aman

5. Common Beginner Mistakes

⚠️ Watch out for these mistakes:

  • KeyError Crashes: Attempting to look up a key that doesn't exist using brackets. Always use .get() if there's any chance the key is missing.
  • Using Lists as Keys: Writing {[1, 2]: "numbers"} will crash with a TypeError: unhashable type: 'list'. Use a tuple {(1, 2): "numbers"} instead.
  • Iterating directly expecting values: Writing for val in my_dict: actually loops through the *keys*, not the values. Use my_dict.values() or my_dict.items().
Interactive Practice

Mini Practice: Catalog Valuation

Create an inventory dictionary where keys are item names and values are nested sub-dictionaries with qty and price. Populate it with "pen" (qty 10, price 1.5) and "book" (qty 5, price 12.0). Loop through the catalog, compute the total value (qty * price), and print a formatted summary statement.

0% complete
Check when done
Quiz

Test Your Understanding

1. What happens if you try to access a non-existent key in a dictionary using bracket notation (e.g. `user["age"]`)?

2. Which of the following is an INVALID dictionary key in Python?

3. Which dictionary method allows you to safely look up keys and specify a default value if they are missing?

🚀 Progression

Dictionaries are complete! You are ready to build **Project 3 — CLI To-Do & Quiz App** next, or proceed to **Strings & Files**.