Before session 2
Dictionaries
Before the next class session, watch the videos made by Chuck Severance from University of Michigan:
Slides
Text-book: chapter 9 - dictionaries
Test
Go to Moodle and take the second test on the video lectures.
Homework
The deadline for homework is Monday. This means, it is a good idea to start with homework already before the session.
This week we are going to get an insight into dictionaries.
NB! Make sure that text files (.txt) are in the same folder as your Python code. Otherwise, Python will not find the file.
Example 1. Meetings
The file meetings.txt contains records of meetings. Each number in the file indicates a day of the week when an appointment takes place (not the number of appointments). The following program reads the data from the file, creates a dictionary and prints out its keys and the values. The keys contain the days of a week, and the values are the numbers of planned appointments.
def day_of_week(n): days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] return days[n-1] try: ffile = open("meetings.txt") except: print("Can't open the file") else: meetings = dict() for line in ffile: try: number = int(line) day = day_of_week(number) meetings[day] = meetings.get(day,0) + 1 except: print("Invalid value") print(meetings)
Example 2. Inventory
The present program helps compile an inventory of all fruits in the shop. Dictionary inventory contains the data about how many fruits there should be in the shop (the fruit names and their amount). The program has a loop which repeatedly asks the user for a fruit. If the fruit is in the dictionary, the program outputs the amount of the fruit in the shop, and asks the user if he wants to update the amount of the fruit. If the fruit is not in the dictionary, the program asks the user about the amount of the fruit and adds a new entry into the dictionary. The program continues asking until the user enters “done”.
inventory = {'apple': 430, 'banana': 312, 'orange': 525, 'pear': 217} while True: fruit = input('Enter a fruit (done to quit): ') if fruit == 'done': break if fruit in inventory: print('Stock information for', fruit, 'is', inventory[fruit]) upd = input('Do you want to update it? (yes/no) ') if upd == 'yes': number = int(input('How many ' + fruit + ' do you have? ')) inventory[fruit] = number else: print('There is no information about', fruit, 'in the shop') number = int(input('How many ' + fruit + ' do you have? ')) inventory[fruit] = number
Homework 2
The deadline is Monday, the 25th of November, 23:59 (Estonian time).