Python Dictionaries and While Loops for Beginners

Introduction

Welcome to the post about Python dictionaries in this series Learn Python by Programming Fundamentals First, where we practice programming fundamentals using the Python programming language.

In this post we will continue to work on the training app and build more functionality by utilizing Python dictionaries.

As you might have guessed, dictionaries are a fundamental part of most programming languages, therefore it’s important to learn how to use them efficiently. As you move on and learn new languages, e.g. Java or C++, the same concepts will apply.

Dictionaries belong to the category fundamental data structures, and are used whenever you want to manage pair-wise information, or a key-value format in programming terms. One example where this is used is in your phone. When you search for a contact, that name is linked to a phone number. We could say that the name has a direct relationship to the number. Whenever these relationships are necessary to represent in a program, a dictionary is usually a good starting point.

Finally, we will build on the concept of loops and look at while loops together with functions as well. Functions are part of a deeper topic that we’ll cover in upcoming posts. The exercises at the end should be a priority to do in order to practice what you’ve learned.

You can read more about dictionaries in the official Python docs at: https://docs.python.org/3/tutorial/datastructures.html

Purpose

The purpose of this article is to help you understand Python dictionaries, functions and while loops and how to use them in your own programs.

Goal

By the end of this post you will be able to

  • Understand what a dictionary is
  • Create and modify dictionaries
  • Use the built-in dictionary methods, such as .get(), .items()
  • Know when you should use a while loop

Prerequisites

You must have Python installed and be able to start IDLE or your IDE to follow along. You should be familiar with how to create modules/script and run a Python script, either from the terminal or the GUI window.

A good starting point is this link: How To Install Python On Your Computer

Additionally you should have finished Python and the Building Blocks of Programming and Python if-statements and loops – how to be lazy

If you found anything difficult in previous posts, don’t hesitate to let us know! Contact Us

Try It Yourself: Python Dictionary Example

Look at the following code, copy and paste it into your IDE of choice, e.g. IDLE or PyCharm. If you run the program, what do you expect to see? Think about it and compare it with the output.

# A simple dictionary with some fruits and their colors
fruit_colors = {
    "apple": "red",
    "banana": "yellow",
    "grape": "purple"
}

# Accessing a value
print("The color of an apple is:", fruit_colors["apple"])

# Adding a new key-value pair
fruit_colors["orange"] = "orange"

# Updating a value
fruit_colors["banana"] = "green"

# Deleting a key-value pair
del fruit_colors["grape"]

# Looping through the dictionary
for fruit, color in fruit_colors.items():
    print(f"{fruit.title()} is {color}.")

Dictionary Concept Breakdown / Code Analysis

Let’s start by inspecting the new syntax. The dictionary definition for fruit_colors starts with curly braces ( {} ), and it’s stored in the variable fruit_colors. Notice the format for defining a dictionary is "key":"value".

The result is a dictionary that contains three keys: apple, banana, grape and three values red, yellow, purple. These are the three pairs in the dictionary: apple+red, banana+yellow and grape+purple.

You can use square brackets [] in order to access a key in the dictionary, which is used in the print-statement. Python also has a built-in method .get() that can be used to retrieve a key’s value.

Finally, in the for-loop we use the dictionary method .items() to access the key and value at the same time. In each iteration, the variables fruit and color are assigned from the dictionary fruit_colors.

Project – Workout App Exercise Details

Now using this new concept, let’s get back to our project again and see if there’s any good use case for a dictionary.

week = 1
schedule = 'Workout A'
exercises = ('Bench press', 'Deadlift', 'Squat', 'Biceps curl')

# New code for dictionaries here soon
# ...
# ...

response = input('Would you like to see all exercises in the training schedule? (Yes/No) ')

selected_exercise = None
if response == 'Yes':
    print('Here are all the exercises:')
elif response == 'No':
    print('Okay, we won’t show any exercises right now.')
else:
    print('Invalid response, please type "Yes" or "No".')

    selected_exercise = input('Which exercise would you like to know more about? ')

if selected_exercise in exercises:
    print(f'You chose {selected_exercise}. This is a fundamental exercise for building strength.')
else:
    print('That exercise is not in the schedule.')


Next we will implement the idea to include a description for each exercise. It’s easy to extend the program and provide more information about an exercise if necessary. For example, to add a video link on how to perform an exercise, you could store that info in a dictionary as well.

In order to put this idea into code, let’s create a new variable called exercise_details that will (you guessed right) hold the description associated with an exercise. Here’s a suggestion, you may change the description text yourself.

exercise_details = {
    "Bench press": "Compound exercise for upper body",
    "Deadlift": "Compound exercise for lower body and core",
    "Squat": "King of exercises, compound and overall legs",
    "Biceps curl": "Isolation exercise for the upper arms"
}

Now we can use two Python built-in methods to query the dictionary. You’ve already seen items() above, Python also provides .keys() and .values() for returning view objects of keys and values respectively.

print(exercises)
print(exercise_details.keys())
print(exercise_details.values())

Output

('Bench press', 'Deadlift', 'Squat', 'Biceps curl')
dict_keys(['Bench press', 'Deadlift', 'Squat', 'Biceps curl'])
dict_values(['Compound exercise for upper body', 'Compound exercise for lower body and core',
               'King of exercises, compound and overall legs', 'Isolation exercise for the upper arms'])

You might have noticed the output of exercises and calling .keys() on the dictionary are rather similar. Remember that exercises is a declared variable that holds a tuple. It’s related to the exercise_details keys by design from the programmer (us). However, the tuple is a different data structure from the view object returned by .keys()

The view object is a dynamic representation of the keys in a dictionary, meaning it always reflects the current state of the dictionary. A tuple however, is immutable, meaning it cannot be changed after it was created.

While Loop – The For-loop’s cousin

The purpose of a while loop is to repeat a code block until a condition is met. This is also called iteration in programming terms. Both the while and for loops are used frequently. Eventually you’ll develop an intuition on when to use them.

The program has to handle errors when users enter information into the program.

If you run the program and press Enter at the first question, the program will continue to the next question without any error control. That is not ideal.

In our program, the idea is not to proceed to the next question, until a valid choice has been made by the user. Therefore we want to repeat any question or choice prompted to the user.

A while loop can repeat a code block until a condition is met. That’s the idea we will implement next in our program.

“”” Until the user has left a valid choice, repeat the code block “””

Let’s first take a look at the anatomy of a while loop.

while boolean-expression:
    code block
    ...etc

This will run the code block repeatedly as long as the boolean expression is True. A boolean expression is an expression that evaluates to either True or False.

Notice the indentation of the code block. It is also possible to use a break statement inside the code block in order to stop the while loop, we will cover an example of this below.

Here’s another example of a while loop that repeatedly prints Hello to the console, don’t run this program (yet).

while True:
    print("Hello")

The word Hello is printed after the first iteration, then the program will start the next iteration, and determine that the condition is still True. Therefore, the program enters the code block again. The code block that prints Hello is executed again, then the next iteration starts and the program repeats this process infinitely.

Workflow of the program:

1. while True mean "yes let's enter the code block"
2. print Hello
3. Go back to step 1) and evaluate whether the expression is True (which it is)
4. print Hello

In contrast to the if statement, we need a mechanism to break out of this loop. The way to handle this is to simply add a break statement in order to exit the loop.

while True:
    print("Hello")
    break # Don't remove this

Now our program will print the word Hello once and immediately finish and exit the loop. If you were to remove that break statement as in the first version, the program would continue to print forever, and you’d have to kill the program somehow, probably by entering Ctrl-C or closing the IDE.

With this in mind, it’s important to construct a while loop such that it doesn’t result in an infinite loop as it’s called. It takes a little practice, but it’s nothing to worry about as continue to improve your understanding of programming loops.

Another common use case of a while is during counting. Here’s what that looks like

counter = 0
while counter < 10:
    print("Counter is at ", counter)
    counter = counter + 1 # Increment the counter in every loop

This doesn’t result in an infinite loop because the counter increases during every iteration. Eventually, it will reach a number that’s greater than 10, thereby evaluating the boolean expression to False. Run the program and see if you can understand how it works.

Before you move on

Experiment and see what changes when the condition is set to 15 instead of 10. If you switch the condition to greater than instead, i.e counter > 10 – what do you notice?

Let’s look at a final example before implementing this in our own program.

Here’s a similar construct to the previous example, but the idea is still to use a break statement to exit the loop.

At first sight, it might look like an infinite loop, but because an exit condition exists, it’s possible for the program to eventually exit, when the user types Quit into the program.

# Almost an infinite loop. It keeps running until the user type Quit however.
while True:
    # Ask the user for input
    answer = input("If you want to quit this loop, please type Quit ")

    if answer == "Quit":
          print("Breaking out the loop...see you next time")
          # Special keyword to exit the loop
          break
    else:
          print("Ok, so you dont want to quit...trying another turn")

In the above example, the break statement is placed after a conditional statement (if), it’s not necessary to place it at the beginning of the loop. It’s up to the programmer to decide under which conditions the loop should break.

Finally, the construct of while True is very common in menu systems and when a program waits for user input.

While Loop Concept Breakdown / Code Analysis

Let’s repeat what we’ve covered so far.

A while loop consists of a condition and a code block. The loop executes the code block as long as the boolean expression evaluates to true.

We saw that a while True: loop repeats a code block forever, the only way to break out of the loop is to execute a break statement somewhere inside the code block. Where and how this is done is up to the programmer. In the previous example this happens when the user enters Quit.

In contrast, while False: would not be useful as the program would never enter the loop, and just skip to the next statements of the program.

Run the examples until you start to understand how they work. If you get stuck, feel free to reach out at -> Contact Us

Project continued – While Loop

Back to our training app project, let’s focus on the first parts of the code. If you remember, we want to validate the answer from the user before moving on.

Therefore, we’ll wrap our first question inside a while True: loop instead of continuing when user enters something invalid. We can also improve the check with the operator in as we saw in the previous post on the in operator.

while True:
    response = input('Would you like to see all exercises in the training schedule? (Yes/No) ')

    if response in ("Yes", "yes"):
        print("Here are all the exercises:")
        for item in exercises:
            print(item)
        break # Break out of the loop, we don't want to repeat the question anymore
    elif response in ("No", "no"):
        print("Cool, no hard feelings!")
        break
    else:
        print("You must answer Yes/No, please try again")

This looks much better. However, we should also notice that after running this program, in the case the user enters No it would be incorrect and weird to continue to the second question. So we’ll have to fix next.

answered_yes = False # Add a new variable
while True:
    response = input(
        "Would you like to see all exercises in the training schedule? (Yes/No) "
    )

    if response in ("Yes", "yes"): # Check membership in the tuple
        answered_yes = True # Store the user's choice
        print("Here are all the exercises:")
        for item in exercises:
            print(item)
        break
    elif response in ("No", "no"):
        print("Cool, no hard feelings!")
        break
    else:
        print("You must answer Yes/No, please try again")

if answered_yes: 
    selected_exercise = input("Which exercise would you like to know more about? ")

    if selected_exercise in exercises:
        print(
            f"You chose {selected_exercise}. This is a fundamental exercise for building strength."
        )
    else:
        print("That exercise is not in the schedule.")


We introduce a new variable called answered_yes that is set to True in the same code block where we print all the exercises, because that’s when we know the answer from the user is Yes. This is also called a state variable, or sometimes a flag variable and it comes in handy when a program must deal with control flow during execution.

Later in the program, we use an if statement to check the value of the state variable, and only if its value is True do we print the second question.

At this stage, we have fair amount of code in our program that works well. We have a small interactive Python program using loops, conditionals, tuples, and dictionaries, not a small feat!

Here’s the complete Python program so far, go ahead and run it in your own IDE.

week = 1
schedule = "Workout A"
exercises = ("Bench press", "Deadlift", "Squat", "Biceps curl")

# Unused variable for now
exercise_details = {
    "Bench press": "Compound exercise for upper body",
    "Deadlift": "Compound exercise for lower body and core",
    "Squat": "King of exercises, compound and overall legs",
    "Biceps curl": "Isolation exercise for the upper arms",
}


answered_yes = False
while True:
    response = input(
        "Would you like to see all exercises in the training schedule? (Yes/No) "
    )

    if response in ("Yes", "yes"):
        answered_yes = True
        print("Here are all the exercises:")
        for item in exercises:
            print(item)
        break  # Break out of the loop, we don't want to repeat the question anymore
    elif response in ("No", "no"):
        print("Cool, no hard feelings!")
        break
    else:
        print("You must answer Yes/No, please try again")

if answered_yes:
    selected_exercise = input("Which exercise would you like to know more about? ")

    if selected_exercise in exercises:
        print(
            f"You chose {exercises[selected_exercise]}. This is a fundamental exercise for building strength.
            {exercise_details[selected_exercise]}.
            "
        )
    else:
        print("That exercise is not in the schedule.")

Exercises

Here are some exercises to try on your own, you can try to building upon the program however you like.

  1. Create a new dictionary with your own keys and values. The dictionary should contain key-value pairs for countries and capitals. Create a second dictionary that stores name and age pairs. Print the dictionaries.
  2. Retrieve a value from your dictionaries using a key and the [] notation. What happens if you specify a non-existent key or make a typo?
  3. Add and update a values in your dictionaries
  4. Add a new key-value pair using the bracket syntax: your_dictionary[key] = value
  5. Update an existing value using the bracket syntax. How is this different from accessing a key with a typo?
  6. Remove an item using del and .pop().
  7. Use a for loop to print all keys in your dictionaries.
  8. Ask the user for a key and check whether it exists in the dictionary.
  9. Write a code block that swaps the keys and values. Remember you can use .keys() and .values().
  10. Use the method .items() on the exercise_details variable. You can decide where in the code to place it and print the contents.
  11. Inside the if selected_exercise in exercises: use another print to print and fetch the value from exercise_details using .get().
  12. Add a third print to print the details, but this time using the [] notation.
  13. Add another alternative to also accept the word “quit”.
  14. Search the Python documentation for string methods, see if you can find a way to remove whitespace from the input string before checking it. So the program should also accept accidental spaces, like “quit “, ” Quit”. It’s enough to handle spaces around the word. https://docs.python.org/3/library/stdtypes.html#string-methods

Summary

In this section, we explored two important Pythoon programming concepts: dictionaries and while loops. These concepts are fundamental building blocks used in many real-world Python programs.

We have also covered Python dictionary methods and learned how dictionaries can be used to store and organize data inside a program.

We have also explored a simplified yet common process for how a program can be developed. We started with an introductory text and expanded it step by step by asking the user a question. We also printed the user’s response.

It’s not easy to build everything at once, we allowed the program details to grow naturally and also handled the control flow of the program better in small improvements. It’s good to think of this process as normal.

In the next section, we’ll continue working with Python control flow and how to write our own functions. Functions are used to break down a program into logical components, and helps us write program that consist of smaller building blocks. We’ll also look into how we can handle text files in Python.

Think about how you want to develop the Training App further. For example, you could let the user enter their own exercise descriptions or store workout history. The sky is the limit!

See you in the next post!