Homework for Week 13
After this week you can
- Manipulate key-value pairs in a dictionary
- Loop over a dictionary
- Use a dictionary to store and retrieve information
- Use dictionary for counting items
Dictionaries
Dictionary is one of the most useful data structures. Since it allows us to represent a relationship between two sets of elements, it has a wide variety of applications. The most straightforward is a lookup in an actual dictionary. A dictionary contains key-value pairs. We can retrieve the value corresponding to a key from the dictionary. In a sense, dictionaries are a generalization of lists, where instead of indices, we have keys.
Before the next class session, watch the videos about dictionaries:
Slides in English
Textbook in English
Quiz
Go to Moodle and take the quiz on video lectures.
Examples
NB! Make sure that your text files (.txt) are in the same folder as your Python code. Otherwise, Python will not find these files.
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 (note that this is not the number of appointments): 1 means Monday, 2 means Tuesday, etc. The following program reads the data from the file, creates a dictionary, and prints its keys and the values on the screen. The keys contain the days of a week, and the values are the numbers of planned appointments on that day.
def day_of_week(n): days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] return days[n-1] ffile = open("meetings.txt") 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)
This is an example of how to count multiple things with a single pass over the file: put them into a dictionary. The function get returns the value corresponding to a key; if that key doesn't exist in a dictionary, it returns 0 (the second argument). The try-except block is needed only for integer conversion.
Inventory
This program helps compile an inventory of all fruits in a shop. Dictionary inventory contains the data about how many fruits there are in the shop (fruit names and their amounts). The program has a loop that repeatedly asks the user for a fruit. If the fruit is in the dictionary, the program outputs the amount of that fruit in the shop and asks the user if he wants to update the fruit's amount. If the fruit is not in the dictionary, the program asks the user about the fruit's amount 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
Note the typical branching which often appears when working with the dictionaries: if the key is in the dictionary, do something with the existing key; and if the key is not in the dictionary, then add a new key-value pair.
Exercises
1. Birthdays
A text file contains birthdays in the format yyyy-mm-dd (see example).
Write a function create_dictionary that takes a filename as a parameter. The function reads the data from the file and creates a dictionary with the following structure. The keys of the dictionary are names of weekdays (i.e. "Monday", "Tuesday" etc), and the value of each key is the number of people who have been born on that weekday. At the end, the function returns the dictionary.
>>> create_dictionary('dates.txt')
{'Saturday': 11, 'Wednesday': 4, 'Friday': 8, 'Thursday': 10, 'Sunday': 5, 'Tuesday': 4, 'Monday': 9}
To find the weekday, use Python's standard module datetime:
import datetime date = datetime.datetime(2022, 4, 29) print(date.weekday())
2. Dictionary
Submit your solutions
Go to Moodle and upload your solutions under homework for Week 13. The programs of exercises 1 and 2 should have the names home1.py and home2.py, respectively.
(The optional part of exercise 1 should be a separate program that can have any name; there is no autotester for the optional part of exercise 2.)
Advice
Programming is breaking of one big impossible task into several very small possible tasks.