Advanced Python

Day 15: Exercise Solutions

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

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

1) Convert the following for loop into a comprehension.

numbers = [1, 2, 3, 4, 5]
squares = []

for number in numbers:
    squares.append(number ** 2)

When constructing a comprehension, we need to think about two things. The value we're trying to add to the new collection, and the looping structure that will allow us to get items from the original collection.

In the code above, the value we want to add to the new collection is number ** 2, or the square of the value of number. We get these numbers by iterating over the numbers list, getting each item from this list, one at a time. As we can see, the loop we're using to do this is:

for number in numbers

Now we have these components, we can put the comprehension together. In this case I'm going to use a list comprehension, since we're trying to make a new list.

Our starting point is this:

numbers = [1, 2, 3, 4, 5]
squares = []

Now, inside the square brackets, we first put the value we want to add, and then the loop.

numbers = [1, 2, 3, 4, 5]
squares = [number ** 2 for number in numbers]

2) Use a dictionary comprehension to create a new dictionary from the dictionary below, where each of the values is title case.

movie = {
    "title": "thor: ragnarok",
    "director": "taika waititi",
    "producer": "kevin feige",
    "production_company": "marvel studios"
}

Let's start by writing this as a regular for loop:

movie = {
    "title": "thor: ragnarok",
    "director": "taika waititi",
    "producer": "kevin feige",
    "production_company": "marvel studios"
}

updated_movie = {}

for key, value in movie.items():
    updated_movie.update({key: value.title()})

Remember that by default we only get the keys when we iterate over a dictionary, so we need to use the items method if we want the keys and the values.

Now, let's break this down like we did before. The thing we want to add is key: value.title() where the for loop is for key, value in movie.items().

We can now put this inside the curly braces next to updated_movie, like so:

movie = {
    "title": "thor: ragnarok",
    "director": "taika waititi",
    "producer": "kevin feige",
    "production_company": "marvel studios"
}

updated_movie = {key: value.title() for key, value in movie.items()}

Of course, because we're using a comprehension, we can reuse the same name if we want.

movie = {
    "title": "thor: ragnarok",
    "director": "taika waititi",
    "producer": "kevin feige",
    "production_company": "marvel studios"
}

movie = {key: value.title() for key, value in movie.items()}