๐Ÿงพ Section 9: Make the SPECIES Lookup Dictionary

๐Ÿ“ Summary (What you will do)

In this section, you will add a lookup dictionary that maps a species name to its class. You will:

  • Create a SPECIES dictionary below the animal classes
  • Store classes as dictionary values
  • Make it easy for the program to create pets dynamically

This is how the game can choose a species by name and build the correct object.


โœ… Checklist (You must complete these)

  • Open pet_manager.py
  • Scroll to just below the species classes (Dog, Cat, Bird)
  • Add the SPECIES dictionary shown below
  • Type the code by hand so you understand the pattern

โœ… No new constants/settings are added in this section, so you do not need to edit the top-of-file constants.


๐ŸŽ“ Core Concepts (New learning for this section)

1) Dictionaries can store classes

A dictionary does not have to store only numbers or strings.
It can store classes too.

That means you can do:

  • Look up a class by name (SPECIES["Dog"])
  • Create a new object with that class (SPECIES["Dog"]("Buddy"))

2) Why this helps the program

Later, the user will choose a species by name.
The program can then look up the class and build the pet without using a long chain of if statements.

3) Type hints for class dictionaries

The type hint:

  • Dict[str, Type[Animal]]

means:

  • Keys are strings (like "Dog")
  • Values are classes that are subclasses of Animal

This makes your code clearer and safer.


๐Ÿ’ป Code to Write (Type this by hand in pet_manager.py)

Directions:

  1. Open pet_manager.py
  2. Find the species classes (Dog, Cat, Bird)
  3. Right below them, type the following code by hand:

Code image: s09-code


๐Ÿง  Code Review & Key Concepts (What important lines do)

The SPECIES dictionary

SPECIES: Dict[str, Type[Animal]] = {
    "Dog": Dog,
    "Cat": Cat,
    "Bird": Bird,
}
  • Each key is a string name the user can pick
  • Each value is the class that will be used to create that pet

This lets the program dynamically create the right species with a single lookup.


๐Ÿงช Test File: s09_test.py

โœ… Create this file

Create a new file in the same folder as pet_manager.py called:

s09_test.py

๐Ÿ’ป Code to write in s09_test.py

Code image: s09-test

๐Ÿง  What this test is doing (and how it works)

  • We pull each class from the SPECIES dictionary by name
  • We create one instance of each class
  • We print the class names to confirm the lookup worked

โœ… Run the test:

python s09_test.py

If the class names match, your lookup dictionary is working correctly.