Part 7: The Alien Encyclopedia — Dictionaries
The Adventures of Ava the Astronaut: Learning Python One Planet at a Time
Part 7: The Alien Encyclopedia — Dictionaries
The Adventures of Ava the Astronaut: Learning Python One Planet at a Time
Cataloging the Cosmos
Ava’s inventory list was perfect for tracking items, but she faced a new challenge. She was meeting all sorts of fascinating alien species and needed to record detailed information about each one. She wanted to be able to quickly look up an alien’s home planet or its primary language just by using its name.
She tried using a list:
alien_info = ["Zorpian", "Planet Zorp", "Chirps and Clicks", 4]“This is confusing, Py,” Ava said. “What does the 4 mean? Is it the number of legs? Eyes? Arms? And if I want to find their language, I have to remember it is at index 2. There must be a better way to label my data.”
“Correct, Commander,” Py beeped. “A list uses numerical indexes, which can be hard to remember. What you need is a Dictionary. A dictionary stores information in key-value pairs. It is like a real-world dictionary: you look up a word (the key) to find its definition (the value).”
The Power of Key-Value Pairs
A dictionary in Python is created using curly braces {}. Each item consists of a unique key followed by a colon and its corresponding value. Key-value pairs are separated by commas.
Let’s create an encyclopedia entry for the Zorpian species.
zorpian = { "species_name": "Zorpian", "home_planet": "Planet Zorp", "language": "Chirps and Clicks", "number_of_eyes": 4, "is_friendly": True}
# Access data using the key — much clearer than an index!print(f"Species: {zorpian['species_name']}")print(f"Home Planet: {zorpian['home_planet']}")print(f"Friendly: {zorpian['is_friendly']}")Output:
Species: ZorpianHome Planet: Planet ZorpFriendly: TrueThis is much clearer than using a list! Instead of a meaningless index like [2], we use a descriptive key like "language". The keys are usually strings, but the values can be any data type: strings, numbers, booleans, lists, or even other dictionaries.
Managing the Encyclopedia
Dictionaries are dynamic, just like lists. You can add, modify, and remove entries as you discover new information.
Adding and Modifying Entries
Adding a new key-value pair is as simple as assigning a value to a new key. If the key already exists, the value is updated.
zorpian = { "species_name": "Zorpian", "home_planet": "Planet Zorp", "number_of_eyes": 4}
# ADD a new entryzorpian["favorite_food"] = "Cosmic Berries"print(f"Added: favorite food is {zorpian['favorite_food']}")
# MODIFY an existing entry (they actually have 5 eyes!)zorpian["number_of_eyes"] = 5print(f"Correction: Zorpians have {zorpian['number_of_eyes']} eyes.")Removing Entries
To remove an entry, you can use the del keyword or the .pop() method.
# Remove an entry using deldel zorpian["number_of_eyes"]
# Remove an entry using pop (also returns the removed value)food = zorpian.pop("favorite_food")print(f"Removed: {food}")Looping Through a Dictionary
One of the most common things you will do with a dictionary is loop through it to display or process all its data. The .items() method gives you both the key and the value in each iteration.
zorpian = { "species_name": "Zorpian", "home_planet": "Planet Zorp", "language": "Chirps and Clicks", "number_of_eyes": 5, "is_friendly": True}
print("--- Zorpian Encyclopedia Entry ---")for key, value in zorpian.items(): print(f" {key}: {value}")print("----------------------------------")Output:
--- Zorpian Encyclopedia Entry --- species_name: Zorpian home_planet: Planet Zorp language: Chirps and Clicks number_of_eyes: 5 is_friendly: True----------------------------------You can also loop through just the keys with .keys() or just the values with .values().
Nested Dictionaries: Data Within Data
What if Ava wants to store information about multiple alien species in a single structure? She can create a dictionary of dictionaries — a nested dictionary.
alien_database = { "Zorpian": { "home_planet": "Planet Zorp", "language": "Chirps and Clicks", "is_friendly": True }, "Gleepoid": { "home_planet": "Gleep Glorp", "language": "Telepathy", "is_friendly": False }}
# Access nested dataprint(f"Zorpian language: {alien_database['Zorpian']['language']}")print(f"Gleepoid friendly? {alien_database['Gleepoid']['is_friendly']}")The first set of brackets ['Zorpian'] gets the inner dictionary for the Zorpian species, and the second set ['language'] gets the specific value from that inner dictionary.
Checking if a Key Exists
Before trying to access a key, it is good practice to check if it exists first. Otherwise, you will get a KeyError if the key is not found.
zorpian = {"species_name": "Zorpian", "home_planet": "Planet Zorp"}
# Use the 'in' keyword to checkif "language" in zorpian: print(f"Language: {zorpian['language']}")else: print("Language data not available.")
# Or use the .get() method, which returns a default value if the key is missinglanguage = zorpian.get("language", "Unknown")print(f"Language: {language}")Mini-Project: “Alien Species Database”
Your mission is to create your own entry for a new alien species in Ava’s encyclopedia.
Your Task:
- Create a dictionary for a brand-new alien species. You can make up the name and all its details!
- Your dictionary should have at least five key-value pairs (e.g.,
species_name,home_planet,number_of_legs,diet,special_ability). - Print the value of at least two properties using their keys.
- Add a new key-value pair (e.g.,
"weakness": "water"). - Modify one of the existing values (e.g., change the
diet). - Use a
forloop with.items()to print the entire, final encyclopedia entry in a clean format.
Bonus Challenge: Create a second alien species dictionary and store both in a nested dictionary called alien_database. Then, write a loop that prints the details of every species in the database.
Mission Complete!
You are now an official intergalactic xenobiologist! You have learned how to use dictionaries to store and manage labeled data using key-value pairs, one of the most powerful and flexible tools in Python. You can add, modify, remove, and loop through dictionary entries, and you even know how to nest dictionaries for complex data structures.
Next, Ava needs to save her mission logs permanently. We will learn how to read and write to files in our next adventure, “The Captain’s Log”! See you in Part 8!
This is Part 7 of a 10-part series: “The Adventures of Ava the Astronaut: Learning Python One Planet at a Time.”