CSC 171 - Introduction to Computer Programming

Lab Assignment #26 - Creating a Dictionary Using a Text File

Due Monday, December 11, 2023

We have already seen that we can open a text file by writing:
my_file = open("phone.txt", 'r')

We can initialize a dictionary as empty by writing
my_dict = {}

We can read our file by writing
for my_record in my_file:
     Some Statements

If our dictionary holds a pair of strings on each line, we can read them within this for loop by writing
name, phone = my_record.split()

If the name is surrounded by quotation marks, we can remove it by writing
name = name[1:-1]

Create a file where each line contains a seven digit ID number (place quotes around it: it should be treated like a string) and a name (also inside quotes). Create a dictionary where the ID number is the key and the name is the value.

[Back to the Lab Assignment List]