Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
← Advanced Software Engineering · Lesson 7 of 10

Module Six

📖 Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
7
Module 6 · Advanced Software Engineer

🗂️ Module 6: Dictionaries, Tuples & Error Handling

Hello, brilliant builder! In Module 5, you learned about classes, objects, and files. Now, we are going to explore even more powerful tools in Python – dictionaries, tuples, and error handling.

Imagine you have a phonebook. You look up a name and find a phone number. That is a dictionary – it stores pairs of keys and values. A tuple is like a list, but it cannot be changed – it's a fixed collection.

Sometimes, your program might make a mistake – like trying to divide by zero. Instead of crashing, we can handle errors gracefully and keep the program running.

By the end of this module, you will be able to use these tools to write more efficient and reliable programs. Let's dive in!

🎯 Learning Objectives

After this module, you will be able to:

  • Explain what a dictionary is and why we use it.
  • Create dictionaries and access, add, and change items.
  • Loop through dictionaries.
  • Explain what a tuple is and when to use it.
  • Differentiate between lists, tuples, and dictionaries.
  • Catch and handle errors using try/except.
  • Write programs that don't crash when something goes wrong.

📖 Warm‑up Story: Amara’s Market Stall

Amara ran a small market stall in Lagos. She sold fruits and vegetables. She had a list of items and their prices. But it was hard to find prices quickly – she had to scan the whole list.

Her friend, a software engineer, said: “Use a dictionary! Instead of a list, you can look up the price directly by the item name.”

Amara created a dictionary where the item name was the key and the price was the value. Now she could find any price instantly – like magic!

She also wanted to keep track of her daily sales in a tuple – a fixed record of the day's total. And when she made a mistake entering a price, she learned to handle errors so her program wouldn't crash.

Now, let's learn how to use these tools in Python!

📘 Lesson 1: What is a Dictionary?

Definition: A dictionary is a collection of key-value pairs. You use a key to look up its value – like a phonebook.

Why is it important? Dictionaries let you store and retrieve data quickly using a unique key.

Simple explanation: Think of a dictionary (the book). You look up a word (the key) and you find its meaning (the value).

Real‑life example: A phonebook – names (keys) and phone numbers (values).

School example: A student ID (key) and the student's name (value).

Home example: A recipe book – dish name (key) and instructions (value).

Nigerian example: A market price list – item name (key) and price (value).

Illustration:

        +----------------------+
        |   Dictionary         |
        +----------------------+
        |  Key    |  Value     |
        +---------+------------+
        | "apple" |  200       |
        | "orange"|  150       |
        | "banana"|  100       |
        +---------+------------+
    

Mini summary: A dictionary stores key-value pairs for fast lookup.

📘 Lesson 2: Creating a Dictionary

Definition: You create a dictionary using curly braces {} and separate keys and values with colons :.

Why is it important? This is the syntax you need to create dictionaries in Python.

Simple explanation: You write {"key": "value"}.

Real‑life example: {"Chidi": "08012345678", "Ama": "08087654321"}

School example: {"Math": 85, "English": 90, "Science": 78}

Home example: {"dad": "John", "mom": "Mary", "sister": "Ada"}

Nigerian example: {"Lagos": 15, "Abuja": 10, "Kano": 8} (city population in millions).

Illustration:

        prices = {
            "apple": 200,
            "orange": 150,
            "banana": 100
        }
        print(prices["apple"])   # 200
    

Mini summary: Use {} to create dictionaries with key-value pairs.

📘 Lesson 3: Accessing Values in a Dictionary

Definition: You access a value by using its key in square brackets [].

Why is it important? This is how you get the data you need from a dictionary.

Simple explanation: Like looking up a word in a dictionary – you use the word to find the meaning.

Real‑life example: phonebook["Chidi"] returns Chidi's phone number.

School example: grades["Math"] returns your Math grade.

Home example: family["dad"] returns your dad's name.

Nigerian example: prices["apple"] returns the price of an apple.

Illustration:

        prices = {"apple": 200, "orange": 150}
        print(prices["apple"])   # 200
    

Mini summary: Use the key in [] to get its value.

📘 Lesson 4: Adding and Changing Items

Definition: You can add a new key-value pair or change an existing value by assigning to the key.

Why is it important? Dictionaries are dynamic – you can update them as needed.

Simple explanation: Like adding a new contact to your phone or updating a phone number.

Real‑life example: Adding a new friend to your contact list.

School example: Updating a grade after a test.

Home example: Adding a new chore to the chore list.

Nigerian example: Adding a new item to your market price list.

Illustration:

        prices = {"apple": 200}
        prices["orange"] = 150   # adding
        prices["apple"] = 250    # changing
        print(prices)   # {'apple': 250, 'orange': 150}
    

Mini summary: You can add or change items by assigning to a key.

📘 Lesson 5: Removing Items from a Dictionary

Definition: You can remove a key-value pair using del or pop().

Why is it important? Sometimes you need to delete data that is no longer needed.

Simple explanation: Like deleting a contact from your phone.

Real‑life example: Removing an old friend from your contact list.

School example: Removing a subject you no longer take.

Home example: Removing a chore that is done.

Nigerian example: Removing an item that is out of stock.

Illustration:

        prices = {"apple": 200, "orange": 150}
        del prices["apple"]   # removes apple
        prices.pop("orange")  # removes orange
        print(prices)   # {}
    

Mini summary: Use del or pop() to remove items.

📘 Lesson 6: Looping Through a Dictionary

Definition: You can loop through keys, values, or both using for loops.

Why is it important? This lets you process all the data in a dictionary.

Simple explanation: Like going through each contact in your phonebook.

Real‑life example: Printing all contacts in your phone.

School example: Displaying all your grades for each subject.

Home example: Listing all the chores for the week.

Nigerian example: Displaying all items in a market price list.

Illustration:

        prices = {"apple": 200, "orange": 150}
        for item, price in prices.items():
            print(item, "costs", price, "naira")
    

Mini summary: Use .items() to loop through key-value pairs.

📘 Lesson 7: What is a Tuple?

Definition: A tuple is a collection of items that is immutable – it cannot be changed after creation.

Why is it important? Tuples are useful for data that should not change, like days of the week.

Simple explanation: A tuple is like a list, but you cannot add, remove, or change items.

Real‑life example: The days of the week – Monday to Sunday.

School example: The subjects you take this term – they are fixed.

Home example: Your family members – a fixed set.

Nigerian example: The states in the South‑East – fixed.

Illustration:

        days = ("Monday", "Tuesday", "Wednesday")
        print(days[0])   # Monday
        # days[0] = "Sunday"   # ERROR! Cannot change
    

Mini summary: Tuples are fixed collections that cannot be changed.

📘 Lesson 8: When to Use a Tuple vs a List

Definition: Use a list when you need to change items; use a tuple when you need a fixed collection.

Why is it important? Choosing the right type makes your program more efficient and safer.

Simple explanation: If you have a list of things that might change, use a list. If they are fixed, use a tuple.

Real‑life example: Your shopping list (list) – you add and remove items. The days of the week (tuple) – fixed.

School example: Your class schedule (list) – it can change. The school subjects (tuple) – fixed.

Home example: Your chores (list) – they change. Your family members (tuple) – fixed.

Nigerian example: Items in your cart (list) – they change. The regions in Nigeria (tuple) – fixed.

Illustration:

        shopping_list = ["bread", "milk", "eggs"]   # list – can change
        weekdays = ("Mon", "Tue", "Wed")            # tuple – fixed
    

Mini summary: Lists are for changeable data; tuples are for fixed data.

📘 Lesson 9: What is Error Handling?

Definition: Error handling is a way to catch and manage errors so your program doesn't crash.

Why is it important? It makes your program robust – it can handle unexpected situations.

Simple explanation: Like wearing a helmet – it protects you if you fall.

Real‑life example: A vending machine – if you insert a wrong coin, it gives it back instead of breaking.

School example: If you make a mistake on a test, your teacher helps you correct it instead of failing you instantly.

Home example: If you spill water, you clean it up – you don't panic.

Nigerian example: A POS machine – if it can't read your card, it says "try again" instead of crashing.

Illustration:

        try:
            result = 10 / 0   # This will cause an error!
        except ZeroDivisionError:
            print("Cannot divide by zero!")
    

Mini summary: Error handling lets your program recover from mistakes.

📘 Lesson 10: The try/except Block

Definition: try and except are used to test a block of code for errors and handle them.

Why is it important? It allows you to catch specific errors and respond appropriately.

Simple explanation: You try to do something, and if it fails, you except (catch) the error and do something else.

Real‑life example: You try to open a door. If it's locked, you use a key (instead of breaking the door).

School example: You try to answer a question. If you don't know, you raise your hand and ask for help.

Home example: You try to cook a new recipe. If it doesn't taste good, you add salt instead of throwing it away.

Nigerian example: You try to withdraw money from an ATM. If the amount is too high, it shows "insufficient balance" instead of crashing.

Illustration:

        try:
            number = int(input("Enter a number: "))
            print("You entered", number)
        except ValueError:
            print("That's not a valid number!")
    

Mini summary: try runs code; except catches and handles errors.

📘 Lesson 11: Catching Specific Errors

Definition: You can catch specific types of errors (like ValueError or ZeroDivisionError) to handle them differently.

Why is it important? It lets you give the user a helpful message instead of a technical error.

Simple explanation: Like a lifeguard – they have different ways to help if you're drowning vs. if you're just tired.

Real‑life example: If a file is not found, you can create it instead of crashing.

School example: If a student enters an invalid answer, the teacher prompts them to try again.

Home example: If you can't find a tool, you look for it instead of giving up.

Nigerian example: If a transaction fails, the app shows a message like "network error" instead of crashing.

Illustration:

        try:
            result = 10 / int(input("Enter divisor: "))
        except ZeroDivisionError:
            print("Cannot divide by zero!")
        except ValueError:
            print("Please enter a number!")
    

Mini summary: Catch specific errors to give better feedback.

📘 Lesson 12: The else and finally Clauses

Definition: else runs if no error occurred; finally runs always, whether an error occurred or not.

Why is it important? They help you structure your code neatly and ensure cleanup actions happen.

Simple explanation: else is like “if everything goes well, do this”. finally is like “no matter what, do this”.

Real‑life example: When you try to cook: else – enjoy the meal; finally – clean the kitchen.

School example: When you write a test: else – get a grade; finally – return the paper.

Home example: When you do laundry: else – fold clothes; finally – put detergent away.

Nigerian example: When you shop: else – pay; finally – leave the store.

Illustration:

        try:
            result = 10 / 2
        except ZeroDivisionError:
            print("Error!")
        else:
            print("Result:", result)
        finally:
            print("Done.")
    

Mini summary: else runs on success; finally always runs.

📘 Lesson 13: Raising Your Own Errors

Definition: You can use raise to trigger an error on purpose when something is wrong.

Why is it important? It lets you enforce rules in your program – like checking that a value is valid.

Simple explanation: Like a teacher saying “Stop!” if you break a rule.

Real‑life example: A vending machine rejects a fake coin.

School example: A teacher rejects an assignment without a name.

Home example: A parent says “No” if you want candy before dinner.

Nigerian example: A bank app raises an error if you try to transfer more than your balance.

Illustration:

        def check_age(age):
            if age < 0:
                raise ValueError("Age cannot be negative!")
            print("Age is", age)

        check_age(10)   # works
        # check_age(-5)  # raises an error
    

Mini summary: Use raise to trigger errors when something is wrong.

📘 Lesson 14: Error Handling with Files

Definition: When working with files, you can use error handling to manage missing files or permissions.

Why is it important? It prevents your program from crashing if a file doesn't exist.

Simple explanation: If you try to read a file that doesn't exist, you can create it instead of crashing.

Real‑life example: If a book is missing from the library, you order a new one.

School example: If your notebook is lost, you get a new one.

Home example: If you can't find a recipe, you search online.

Nigerian example: If a customer's record is not in the system, you create a new one.

Illustration:

        try:
            file = open("data.txt", "r")
            content = file.read()
            file.close()
        except FileNotFoundError:
            print("File not found. Creating a new one.")
            file = open("data.txt", "w")
            file.write("New file created.")
            file.close()
    

Mini summary: Use error handling to manage file operations safely.

📘 Lesson 15: Putting It All Together

Definition: A real program uses dictionaries, tuples, and error handling together to solve problems.

Why is it important? This is how professional software engineers build robust applications.

Simple explanation: You use dictionaries to store data, tuples for fixed data, and error handling to manage mistakes.

Real‑life example: A weather app uses a dictionary to store city‑temperature pairs, tuples for fixed data like months, and error handling for network issues.

School example: A gradebook uses a dictionary for student grades, a tuple for subjects, and error handling for invalid inputs.

Home example: A recipe app uses a dictionary for recipes, a tuple for ingredients that are always needed, and error handling for missing files.

Nigerian example: A banking app uses dictionaries for customer data, tuples for fixed currency types, and error handling for transaction errors.

Illustration:

        # Dictionary for prices
        prices = {"apple": 200, "orange": 150}

        # Tuple for fixed categories
        categories = ("Fruits", "Vegetables")

        # Error handling for input
        try:
            item = input("Enter item: ")
            print("Price:", prices[item])
        except KeyError:
            print("Item not found!")
    

Mini summary: Combining dictionaries, tuples, and error handling creates powerful programs.

📚 Key Vocabulary

WordSimple Definition
DictionaryA collection of key-value pairs.
KeyA unique identifier used to look up a value.
ValueThe data associated with a key.
TupleA fixed, unchangeable collection.
ImmutableCannot be changed after creation.
Error HandlingManaging errors to prevent crashes.
try/exceptBlocks used to catch and handle errors.
raiseTrigger an error on purpose.
KeyErrorError when a key is not found in a dictionary.
ValueErrorError when a value is invalid.

🧠 Important Concepts

  • Lookup Time: Dictionaries are very fast for looking up values by key – they use a technique called hashing.
  • Immutability: Tuples are immutable, which means they are safe to use as keys in dictionaries.
  • Graceful Degradation: Error handling allows a program to continue running even when some parts fail.
  • Defensive Programming: Writing code that anticipates and handles possible errors.

👣 Step‑by‑Step Explanations

How to use a dictionary

  1. Create it with {key: value}.
  2. Access values with dict[key].
  3. Add/change with dict[new_key] = value.
  4. Remove with del dict[key].
  5. Loop with for key, value in dict.items():.

How to handle errors

  1. Place risky code inside a try block.
  2. Catch specific errors with except ErrorType:.
  3. Add an else block for success.
  4. Add a finally block for cleanup.
  5. You can also raise errors to enforce rules.

🌍 Real‑life Examples

  • Dictionary: A student database – student IDs (keys) and names (values).
  • Tuple: The coordinates of a location – (latitude, longitude) – fixed.
  • Error Handling: A calculator – handles division by zero gracefully.

🇳🇬 Nigerian Examples

  • Dictionary: A market price list – item names and prices.
  • Tuple: The six geopolitical zones – fixed.
  • Error Handling: A banking app – handles invalid PIN entries without crashing.
  • Dictionary: A student record system – NIN (key) and student details (value).

🎮 Fun Examples Children Can Relate To

  • Dictionary: In Minecraft, item names (keys) and their IDs (values).
  • Tuple: The coordinates of your house – (x, y, z) – fixed.
  • Error Handling: A game that doesn't crash when you try to walk into a wall.

🏠 Everyday Examples

  • Dictionary: Your phone's contact list – names and numbers.
  • Tuple: Your home address – fixed.
  • Error Handling: Your microwave – it beeps if you try to run it empty.

🧑‍🏫 Teacher Notes

This module introduces powerful data structures and error handling. Use real‑world analogies (phonebooks, contact lists) to explain dictionaries. Emphasise the immutability of tuples. For error handling, demonstrate common errors and how to catch them. Encourage students to write programs that handle errors gracefully.

👪 Parent Tips

Encourage your child to think about data as key‑value pairs – e.g., “What is the key for your phone number?”. Discuss the difference between changeable (list) and fixed (tuple) data. Talk about how error handling is like planning for mistakes – it's a sign of a good engineer.

✨ Interesting Facts

  • Dictionaries are also called “maps” or “hash tables” in other languages.
  • Tuples use less memory than lists because they are immutable.
  • Error handling is a key part of professional software development.

💡 Did You Know?

  • Did you know that dictionary keys can be numbers, strings, and even tuples?
  • Did you know that Python’s error messages are actually helpful if you read them?
  • Did you know that many Nigerian fintech apps use dictionaries extensively for transaction data?

🔔 Remember This

  • Dictionaries store key-value pairs for fast lookup.
  • Tuples are fixed – they cannot be changed.
  • Use lists for changeable data, tuples for fixed data.
  • Error handling prevents crashes – always plan for mistakes.
  • Use try/except to catch errors.

⚠️ Common Mistakes

  • Using a list as a dictionary key – lists are mutable and cannot be keys. Use tuples instead.
  • Forgetting to handle KeyError – when accessing a key that doesn't exist.
  • Using == instead of = when adding items – assignment vs comparison.
  • Catching a generic Exception – it's better to catch specific errors.
  • Not using finally for cleanup – like closing files.

✅ Best Practices

  • Use .get() to safely access dictionary values (returns None if key missing).
  • Catch specific exceptions rather than using a bare except.
  • Use tuples for fixed data – they are safer and faster.
  • Always close files, even if an error occurs – use finally or with.
  • Write user‑friendly error messages.

📊 Diagrams & Tables

Dictionary Lookup

        +--------+     +---------+
        |  Key   | --> |  Value  |
        +--------+     +---------+
        | "apple"|     |  200    |
        | "orange"|    |  150    |
        | "banana"|    |  100    |
        +--------+     +---------+
    

Comparison Table: List vs Tuple vs Dictionary

FeatureListTupleDictionary
Mutable?YesNoYes
Ordered?YesYesYes (Python 3.7+)
Access byIndexIndexKey
Example[1,2,3](1,2,3){'a':1}

Error Handling Flowchart

        +-------------------+
        |   try block       |
        |   (risky code)    |
        +--------+----------+
                 |
        +--------v----------+
        |   Error occurred? |
        +---+------------+--+
            |            |
           Yes           No
            |            |
            v            v
        +--------+   +--------+
        | except |   |  else  |
        | handle |   | (done) |
        +--------+   +--------+
            |            |
            +------+-----+
                   |
            +------v-----+
            |  finally   |
            | (clean up) |
            +------------+
    

📝 End‑of‑Module Summary

You have completed Module 6 – you are now equipped with some of the most powerful tools in Python! You learned about dictionaries – key‑value stores for fast data access. You discovered tuples – fixed collections that are safe and efficient. You also learned error handling – how to make your programs robust and user‑friendly.

These concepts are used in almost every real‑world application – from web apps to games to banking systems. You are building a solid foundation for advanced software engineering.

Keep exploring and practicing – you are doing amazing!

❓ Frequently Asked Questions

  1. What is a dictionary in Python? A collection of key‑value pairs.
  2. How do I access a value in a dictionary? Use the key in square brackets: dict[key].
  3. What is the difference between a list and a tuple? Lists are mutable (changeable); tuples are immutable (fixed).
  4. When should I use a tuple? For fixed data that should not change.
  5. What is error handling? Managing errors so the program doesn't crash.
  6. What is try/except? A way to catch and handle errors.
  7. What is a KeyError? An error that occurs when you try to access a key that doesn't exist.
  8. How can I safely access a dictionary key? Use .get(key) – it returns None if the key is missing.
  9. What does raise do? It triggers an error on purpose.
  10. Why is error handling important? It makes programs more reliable and user‑friendly.

🤔 Review Questions

  1. What is a dictionary?
  2. How do you create a dictionary?
  3. How do you access a value in a dictionary?
  4. How do you add a new key‑value pair?
  5. How do you remove a key‑value pair?
  6. What is a tuple?
  7. What is the difference between a list and a tuple?
  8. When would you use a tuple instead of a list?
  9. What is error handling?
  10. What is a try/except block?
  11. What is a KeyError?
  12. What is the purpose of the else clause in error handling?
  13. What is the purpose of the finally clause?
  14. How do you raise an error?
  15. Why is it important to handle errors?

📝 Fill‑in‑the‑Blank

  1. A ______ stores key‑value pairs.
  2. You use a ______ to look up a value in a dictionary.
  3. A ______ is a fixed, unchangeable collection.
  4. Tuples are ______ – they cannot be changed.
  5. ______ is the process of managing errors in a program.
  6. You use ______ to catch and handle errors.
  7. ______ is an error that occurs when a key is not found.
  8. You can ______ an error to trigger it on purpose.
  9. The ______ clause runs if no error occurs.
  10. The ______ clause always runs, whether an error occurs or not.

✅ True or False

  1. Dictionaries are unordered collections. (False – they are ordered in Python 3.7+)
  2. Tuples can be changed after creation. (False)
  3. Lists are immutable. (False – lists are mutable)
  4. Error handling prevents program crashes. (True)
  5. try/except is used for loops. (False)
  6. A KeyError occurs when you try to access a missing key. (True)
  7. finally runs only if an error occurs. (False – it always runs)
  8. You can use raise to trigger an error on purpose. (True)
  9. Dictionaries are faster than lists for lookups. (True)
  10. Tuples use more memory than lists. (False – they use less)

🔘 Multiple Choice

  1. What is a dictionary?
    A) A list of items
    B) A collection of key‑value pairs
    C) A type of loop
    D) A function
    Answer: B
  2. How do you create a dictionary?
    A) []
    B) {}
    C) ()
    D) <>
    Answer: B
  3. What is a tuple?
    A) A mutable collection
    B) An immutable collection
    C) A dictionary
    D) A function
    Answer: B
  4. What is error handling?
    A) Ignoring errors
    B) Managing errors to prevent crashes
    C) Deleting errors
    D) Printing errors
    Answer: B
  5. Which keyword is used to catch errors?
    A) try
    B) except
    C) finally
    D) raise
    Answer: B
  6. What is a KeyError?
    A) An error when a key is missing
    B) An error when a value is missing
    C) An error in a loop
    D) An error in a tuple
    Answer: A
  7. What does raise do?
    A) Catches an error
    B) Triggers an error on purpose
    C) Prints a message
    D) Ends the program
    Answer: B
  8. When would you use a tuple?
    A) For data that changes
    B) For fixed data
    C) For loops
    D) For functions
    Answer: B
  9. What does the else clause do in error handling?
    A) Runs if an error occurs
    B) Runs if no error occurs
    C) Always runs
    D) Raises an error
    Answer: B
  10. What does the finally clause do?
    A) Runs if an error occurs
    B) Runs if no error occurs
    C) Always runs
    D) Raises an error
    Answer: C
  11. Which of these is a valid dictionary key?
    A) List
    B) Tuple
    C) Dictionary
    D) All of the above
    Answer: B (tuples are hashable)
  12. How do you safely access a dictionary key?
    A) dict[key]
    B) dict.get(key)
    C) dict.pop(key)
    D) del dict[key]
    Answer: B
  13. What is the difference between a list and a tuple?
    A) Lists are immutable; tuples are mutable
    B) Lists are mutable; tuples are immutable
    C) Both are mutable
    D) Both are immutable
    Answer: B
  14. Which of these is NOT a valid dictionary operation?
    A) Adding a key‑value pair
    B) Changing a value
    C) Removing a key‑value pair
    D) Sorting the keys
    Answer: D (dictionaries are not sorted by default)
  15. What is the purpose of error handling?
    A) To make programs faster
    B) To make programs more reliable
    C) To make programs longer
    D) To make programs harder to read
    Answer: B

🔗 Matching Exercises

TermDefinition
1. DictionaryA. A fixed, unchangeable collection
2. TupleB. A collection of key‑value pairs
3. KeyErrorC. Used to catch errors
4. exceptD. Error when a key is missing
5. raiseE. Trigger an error on purpose

Answers: 1‑B, 2‑A, 3‑D, 4‑C, 5‑E

✏️ Short Answer Questions

  1. Explain what a dictionary is and give an example.
  2. What is the difference between a list and a tuple?
  3. What is error handling and why is it important?
  4. How do you catch a specific error like KeyError?
  5. When would you use a tuple instead of a list?

🎭 Scenario‑based Exercises

Scenario 1: You are building a dictionary to store student grades. The keys are student names, and the values are grades. Write code to add a new student, update a grade, and safely retrieve a grade.

Scenario 2: You are reading a file that might not exist. Write code that handles the FileNotFoundError and creates the file if it doesn't exist.

👥 Group Activity

In groups, create a dictionary of 10 items and their prices (in naira). Write functions to add, remove, and update items. Then, write a function that displays all items and prices. Use error handling to manage invalid inputs.

🧑 Individual Activity

Write a Python program that creates a tuple of your favourite foods. Then, create a dictionary that maps each food to its price. Use error handling to check if a user‑entered food is in the dictionary.

💬 Classroom Discussion Questions

  1. Why are dictionaries faster than lists for lookups?
  2. When would you prefer to use a dictionary over a list?
  3. How does error handling improve user experience?
  4. Can you think of a situation where raising your own error would be useful?

🛠️ Mini Project

Build a Simple Phonebook: Create a program that uses a dictionary to store contacts (name → phone number). Implement functions to add, delete, update, and search for contacts. Use error handling for cases like a contact not found or invalid input.

📋 Practical Assignment

Write a Python program that reads a text file containing key‑value pairs (one per line, separated by commas). Store them in a dictionary. Then, allow the user to search for a key and display its value. Handle errors if the file doesn't exist or a key is missing.

🏆 Challenge Exercise

Write a Python program that creates a nested dictionary – a dictionary where the values are also dictionaries. For example, a dictionary of students, where each student has a dictionary of subjects and grades. Implement functions to add a student, add a grade, and calculate the average grade for a student. Use error handling for all operations.

📌 Quiz Answers

Fill‑in‑the‑Blank: 1. dictionary, 2. key, 3. tuple, 4. immutable, 5. Error handling, 6. try/except, 7. KeyError, 8. raise, 9. else, 10. finally.

True/False: 1F, 2F, 3F, 4T, 5F, 6T, 7F, 8T, 9T, 10F.

Multiple Choice: 1B, 2B, 3B, 4B, 5B, 6A, 7B, 8B, 9B, 10C, 11B, 12B, 13B, 14D, 15B.

🎁 Key Takeaways

  • Dictionaries store key‑value pairs for fast lookups.
  • Tuples are immutable and are used for fixed data.
  • Error handling makes programs robust and user‑friendly.
  • Always catch specific errors rather than generic ones.
  • Use dictionaries to model real‑world mappings (like phonebooks).

🔜 Preparation for Module 7

In Module 7, you will learn about recursion, higher‑order functions, and working with JSON. These are advanced topics that will take your Python skills to the next level. To prepare, think about problems that can be broken down into smaller versions of themselves – like searching a folder inside a folder.

You are on an incredible journey – keep going! See you in Module 7!

🏆 Get Certified

🔒

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (₦2,000 or 20,000 coins), and get a verified certificate with your name on it.

🎓 Sign Up to Get Certified
🛠️ Practice Tools
Hands-on simulators & labs - subscription required.
→
🎯 Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
→