Working with data

Day 10: Exercise Solutions

Python Guru with a screen instead of a face, typing on a computer keyboard with a light green background to match the day 10 image.

Here are our solutions for the day 10 exercises in the 30 Days of Python series. Make sure you try the exercises yourself before checking out the solutions!

1) Below is a tuple describing an album. Convert this outer tuple to a dictionary with four keys.

(
    "The Dark Side of the Moon",
    "Pink Floyd",
    1973,
    (
        "Speak to Me",
        "Breathe",
        "On the Run",
        "Time",
        "The Great Gig in the Sky",
        "Money",
        "Us and Them",
        "Any Colour You Like",
        "Brain Damage",
        "Eclipse"
    )
)

The tuple above contains four pieces of information: an album title, the name of the band, the year the album was released, and a track list.

Each key of our dictionary is going to have to describe this information, so I'm going to use the following keys: "title", "artist", "year", and "tracks". Feel free to choose different key names if you like.

Now it's just a case of mapping the values to these keys.

{
    "title": "The Dark Side of the Moon",
    "artist": "Pink Floyd",
    "year": 1973,
    "tracks": (
        "Speak to Me",
        "Breathe",
        "On the Run",
        "Time",
        "The Great Gig in the Sky",
        "Money",
        "Us and Them",
        "Any Colour You Like",
        "Brain Damage",
        "Eclipse"
    )
}

Remember that each key and value are separated by a colon (:), and each key value pair are separated by a comma.

2) Iterate over the keys and values of the dictionary you create in exercise 1. For each key and value, you should print the name of the key, and then the value alongside it.

To start with, let's assign this dictionary to a variable so we can refer to it more easily.

album = {
    "title": "The Dark Side of the Moon",
    "artist": "Pink Floyd",
    "year": 1973,
    "tracks": (
        "Speak to Me",
        "Breathe",
        "On the Run",
        "Time",
        "The Great Gig in the Sky",
        "Money",
        "Us and Them",
        "Any Colour You Like",
        "Brain Damage",
        "Eclipse"
    )
}

Remember that, by default, when we iterate over a dictionary we're only going to get the keys back. This isn't what we want in this case, because we want the keys and the values.

The best way to get both the keys and the values is to call the items method on the dictionary when we want to iterate over it.

Then it's just a case of assigning these values to two variables and referencing them in the loop body.

for key, value in album.items():
    print(f"{key}: {value}")

3) Delete the track list and year of release from the dictionary you created. Once you've done this, add a new key to the dictionary to store the date of release.

We have plenty of options for deleting items from dictionaries. Here I'm going to use the del keyword.

Once again, we're going to make use of the variable name, album, for our dictonary.

album = {
    "title": "The Dark Side of the Moon",
    "artist": "Pink Floyd",
    "year": 1973,
    "tracks": (
        "Speak to Me",
        "Breathe",
        "On the Run",
        "Time",
        "The Great Gig in the Sky",
        "Money",
        "Us and Them",
        "Any Colour You Like",
        "Brain Damage",
        "Eclipse"
    )
}

Using del, we can remove the two keys like so:

album = {
    "title": "The Dark Side of the Moon",
    "artist": "Pink Floyd",
    "year": 1973,
    "tracks": (
        "Speak to Me",
        "Breathe",
        "On the Run",
        "Time",
        "The Great Gig in the Sky",
        "Money",
        "Us and Them",
        "Any Colour You Like",
        "Brain Damage",
        "Eclipse"
    )
}

del album["year"]
del album["tracks"]

Now we have to add a new key and value to the dictionary. I'm going to call it release_date, and the release date for The Dark Side of the Moon was March 1st, 1973.

album = {
    "title": "The Dark Side of the Moon",
    "artist": "Pink Floyd",
    "year": 1973,
    "tracks": (
        "Speak to Me",
        "Breathe",
        "On the Run",
        "Time",
        "The Great Gig in the Sky",
        "Money",
        "Us and Them",
        "Any Colour You Like",
        "Brain Damage",
        "Eclipse"
    )
}

del album["year"]
del album["tracks"]

album["release_date"] = "March 1st, 1973"

4) Try to retrieve one of the values you deleted from the dictionary. This should give you a KeyError. Once you've tried this, repeat the step using the get method to prevent the exception being raised.

For the dictionary above, we can try to access either "year" or "tracks". It doesn't matter which.

First, let's try to print the value associated with the "year" key.

album = {
    "title": "The Dark Side of the Moon",
    "artist": "Pink Floyd",
    "year": 1973,
    "tracks": (
        "Speak to Me",
        "Breathe",
        "On the Run",
        "Time",
        "The Great Gig in the Sky",
        "Money",
        "Us and Them",
        "Any Colour You Like",
        "Brain Damage",
        "Eclipse"
    )
}

del album["year"]
del album["tracks"]

album["release_date"] = "March 1st, 1973"

print(album["year"])

This is going to give us a KeyError as expected:

Traceback (most recent call last):
  File "main.py", line 24, in <module>
    print(album["year"])
KeyError: 'year'

Let's comment this line out so it doesn't crash our program. Now let's try to access the "year" key using get. In this case, I'm going to specify a default value of "Unknown".

album = {
    "title": "The Dark Side of the Moon",
    "artist": "Pink Floyd",
    "year": 1973,
    "tracks": (
        "Speak to Me",
        "Breathe",
        "On the Run",
        "Time",
        "The Great Gig in the Sky",
        "Money",
        "Us and Them",
        "Any Colour You Like",
        "Brain Damage",
        "Eclipse"
    )
}

del album["year"]
del album["tracks"]

album["release_date"] = "March 1st, 1973"

# print(album["year"])

print(album.get("year", "Unknown")

Now instead of getting an exception, we get "Unknown" printed to the console.