A201 Introduction to Programming 1

A201 Lab 11

Date: Tuesday, November 14, 2023.
Due Date: Tuesday, November 21, 2023.

Goal: to use the dictionary data structure in Python.

Create a Python file called lab11.py and add your name and the lab number as a comment at the top.

Ex. 1. Using a for loop with a dictionary

a. Dictionary access

Write a function acceptLogin(users, name, password) that receives three parameters. The first one is a dictionary where the keys are user names and the values associated with them are passwords. The second parameter is a user name and the third one a password, both strings.

The function should return True if the given password for this user matches the one stored in the dictionary for the name, and False if not. Note that this function does not require a loop.

Write a main function where you declare a dictionary of user with at least 5 names and some fictional passwords for them. Then ask the user to enter their name and password, call the function acceptLogin, and if it returns True then print "Login successful" and if not, the opposite.

b. Dictionary traversal

Write a function printPets that receives a dictionary of pets where the key is the pet name and the value associated with it is the type of animal it is. The function should print all the pets in the dictionary, each on a line, using a text such as "Ziggy is a spider".

The function should use a simple for loop that goes over the dictionary and prints the key followed by the text "is a" and followed by the value.

In the main, create a dictionary containing such pairs and store it in a variable. For example, the dictionary could start with

pets = {'Ziggy': 'spider', ...}

Add at least 4 entries in this dictionary, then call the function printPets with this variable.

c. For loop over values

Write a function that receives a dictionary as a parameter and prints all of its items in the order of the values. The header of the function should be:

def printByValues(D):

For this, first copy the function searchValue seen in class:

def searchValue(Dict, value):
    for k in Dict:
        if Dict[k] == value:
            return k
    return None

Then extract the values from the dictionary in the form a list by doing

list(D.values())

and store the result in a variable V. Call the built-in function sort on this variable.

Then use a for loop over the list V. For every value, find its matching key by calling the function searchValue and then print the key and the value with ":" in between.

Add a test for this function in the main with the dictionary of user names.

Lab Submission

Upload the file lab11.py in Canvas, Assignments, Homework 11. You can wait until you finish the homework to upload all the files at the same time.