Chapter 9: Space Dictionaries (Dictionaries)

Welcome back, Space Explorer! As we’re journeying through the vast cosmic ocean, we’re encountering an ever-growing variety of celestial objects. Not only stars, but also planets, asteroids, and even alien species! To keep track of this information efficiently, we’ll need a more advanced tool. Enter Python dictionaries!

A Python dictionary is a data type that allows us to store key-value pairs. It’s like a real-life dictionary, where you look up a word (the key) and find its definition (the value). In our context, a key could be a celestial object’s designation, and the value could be its properties. So, without further ado, let’s dive into the world of dictionaries!

Introduction to Dictionaries

In Python, a dictionary is created by enclosing key-value pairs in curly braces {}. Each pair is written as key: value, and pairs are separated by commas. Here’s an example:

1 alien_species = {
2     "name": "Zorgon",
3     "color": "green",
4     "num_eyes": 3,
5     "planet_of_origin": "Zorgon Prime"
6 }

In this dictionary, we have four keys: “name”, “color”, “num_eyes”, and “planet_of_origin”. Each key is associated with a value. We can retrieve a value by indexing the dictionary with its corresponding key:

1 alien_name = alien_species["name"]
2 print(alien_name)  # This will print "Zorgon"

Just like lists, dictionaries are mutable, meaning we can add, remove, or change items after the dictionary is created.

Adding and Modifying Dictionary Entries

To add a new entry to a dictionary, we simply assign a value to a new key:

1 alien_species["num_legs"] = 2

Now, if we print alien_species, it will include the key “num_legs” with its value 2.

To modify an entry, we assign a new value to an existing key:

1 alien_species["color"] = "blue"

Now, the value of “color” in alien_species has changed to “blue”.

Removing Entries from a Dictionary

We can remove entries from a dictionary using the del statement:

1 del alien_species["num_legs"]

After this line of code, “num_legs” will no longer be a key in alien_species.

Dictionary Methods

Python provides several methods that we can use with dictionaries:

  • keys(): This returns a view object that displays a list of all the keys in the dictionary.
  • values(): This returns a view object that displays a list of all the values in the dictionary.
  • items(): This returns a view object that displays a list of the dictionary’s key-value tuple pairs.
  • get(key[, default]): This returns the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

Let’s see some of these methods in action:

1 print(alien_species.keys())  # This will print all the keys
2 print(alien_species.values())  # This will print all the values
3 print(alien_species.items())  # This will print all the key-value pairs
4 
5 # Let's use get() to find the number of eyes, with a default value of 2
6 num_eyes = alien_species.get("num_eyes", 2)
7 print(num_eyes)  # This will print 3

Project: Alien Species Log

Armed with our new knowledge of Python dictionaries, let’s upgrade our star catalog to an alien species log. Our log will keep track of different alien species we encounter on our journey. For each species, we’ll record its name, color, number of eyes, and planet of origin.

 1 # Our alien species log is a list of dictionaries.
 2 # Each dictionary represents an alien species.
 3 alien_species_log = []
 4 
 5 # Function to add an alien species to the log
 6 def add_species(name, color, num_eyes, planet_of_origin):
 7     species = {
 8         "name": name,
 9         "color": color,
10         "num_eyes": num_eyes,
11         "planet_of_origin": planet_of_origin
12     }
13     alien_species_log.append(species)
14 
15 # Function to display the alien species log
16 def display_log():
17     for species in alien_species_log:
18         print(species["name"], "from", species["planet_of_origin"])
19         print("Color:", species["color"])
20         print("Number of eyes:", species["num_eyes"])
21         print()  # Print a blank line for readability
22 
23 # Let's add some alien species to our log
24 add_species("Zorgon", "green", 3, "Zorgon Prime")
25 add_species("Blorb", "blue", 1, "Blorb Majora")
26 add_species("Glarg", "red", 5, "Glarg 7")
27 
28 # And display the log
29 display_log()

This program first adds a few alien species to the log, then prints out each species’ information.

Congratulations, you’ve just built an alien species log with Python dictionaries!

In the next chapter, we’ll be dealing with scenarios that repeat many times, and learning how to handle them efficiently using loops. Until then, keep exploring and coding!